[phpBB Debug] PHP Warning: in file [ROOT]/phpbb/session.php on line 580: sizeof(): Parameter must be an array or an object that implements Countable
[phpBB Debug] PHP Warning: in file [ROOT]/phpbb/session.php on line 636: sizeof(): Parameter must be an array or an object that implements Countable
Unofficial UNIT-e Forum • Max Value Between 2 Or More Tables
Page 1 of 1

Max Value Between 2 Or More Tables

Posted: Mon Mar 13, 2017 2:40 pm
by robinwilson16
Just thought I would share some code. I had to retrieve the highest (MAX) value by combining data from multiple tables together.

If in the same table then a simple MAX works however this does not as two tables are involved and MAX only takes a single input:

Code: Select all

Highest = MAX ( TBL1.Value, TBL2.Value ) -- Does Not Work!
The workaround is to wrap these values into a sub-query:

Code: Select all

SELECT
	--Highest = MAX ( TBL1.Value, TBL2.Value ) -- Does Not Work!
	Highest = ( SELECT MAX ( v ) FROM ( VALUES ( TBL1.Value ), ( TBL2.Value ), ( 0 ) ) AS VALUE ( v ) ) -- Does Work
FROM 
(
	SELECT
		Value = 20
) TBL1
INNER JOIN (
	SELECT
		Value = 40
) TBL2 ON 1 = 1
The output of the above is 40:
Max from Multiple Tables.PNG
Max from Multiple Tables.PNG (18.91 KiB) Viewed 1549 times