I need to query the maximum ID from two tables and I need to take the ID of whichever is larger. i am using sqlserver.
Queries:
SELECT MAX(a.ID)
FROM tableA a
SELECT MAX(b.ID)
FROM tableB b
If tableA
's maximum ID is 20 and tableB
's maximum ID is 30 then the UNION
of both the tables query should return only 30.
Is it possible to combine both the queries into a single query to return maximum ID?
select id from T1 where price in( select max(price) from( select max(price) as price from T1 union select max(price) as price from T2 union select max(price) as price from T3 ) temp ) union select id from T2 where price in( select max(price) from( select max(price) as price from T1 union select max(price) as price from ...
No, we can't use a MAX(COUNT(*) and we can not layer aggregate functions on top of one another in the same SELECT clause.
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables.
To get the maximum value from three different columns, use the GREATEST() function. Insert some records in the table using insert command. Display all records from the table using select statement.
This is based on what you said, UNION
both tables and get the maximum value.
SELECT max(ID)
FROM
(
select max(ID) ID from tableA
UNION
select max(ID) ID from tableB
) s
or
SELECT max(ID)
FROM
(
select ID from tableA
UNION
select ID from tableB
) s
SELECT MAX(id)
FROM (SELECT ID FROM tableA
UNION
SELECT ID FROM tableB) AS D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With