Max Value Between 2 Or More Tables

Any handy code snippets you wish to share with the community
Post Reply [phpBB Debug] PHP Warning: in file [ROOT]/vendor/twig/twig/lib/Twig/Extension/Core.php on line 1266: count(): Parameter must be an array or an object that implements Countable
User avatar
robinwilson16
Site Admin
Posts: 185
Joined: Sun Oct 16, 2016 6:46 pm
Forename: Robin
Surname: Wilson
College Name: FEA
Position: MIS Consultant
LinkedIn Profile: https://www.linkedin.com/in/robinwilson16
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/twig/twig/lib/Twig/Extension/Core.php on line 1266: count(): Parameter must be an array or an object that implements Countable

Max Value Between 2 Or More Tables

Post by robinwilson16 » Mon Mar 13, 2017 2:40 pm

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 1462 times

Post Reply [phpBB Debug] PHP Warning: in file [ROOT]/vendor/twig/twig/lib/Twig/Extension/Core.php on line 1266: count(): Parameter must be an array or an object that implements Countable
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/twig/twig/lib/Twig/Extension/Core.php on line 1266: count(): Parameter must be an array or an object that implements Countable
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/twig/twig/lib/Twig/Extension/Core.php on line 1266: count(): Parameter must be an array or an object that implements Countable

Who is online

Users browsing this forum: No registered users and 1 guest