如何从2个表中获取最大值

时间:2011-10-16 10:16:47

标签: sql sql-server sql-server-2005

使用Sql Server

我想从两张表中获取最大值

表1

ID Total

101 100
102 600
.....

表2

ID Total

101 300
102 400
....

我希望根据id

从2个表中获取最大值

预期产出

ID Total

101 300 (max value in table2)
102 600 (max value in table1)
....
...

如何进行查询

需要查询帮助

3 个答案:

答案 0 :(得分:10)

SELECT
   ID, MAX(Total)
FROM
    (
    SELECT ID, Total FROM Table1
    UNION ALL
    SELECT ID, Total FROM Table2
    ) foo
GROUP BY
   ID

答案 1 :(得分:2)

; with
q_00 as (
select id, Total from Tbl_1
union all
select id, Total from Tbl_2
)
select id, max(Total)
from q_00
group by id
order by id ;

答案 2 :(得分:1)

另一个值得考虑的选择可能是

WITH T(ID, Total)
     AS (SELECT ID,
                MAX(Total)
         FROM   Table1
         GROUP  BY ID
         UNION ALL
         SELECT ID,
                MAX(Total)
         FROM   Table2
         GROUP  BY ID)
SELECT ID,
       MAX(Total) AS Total
FROM   T
GROUP  BY ID  

如果ID,Total在两个表中被编入索引,可能会提供更好的计划(未经测试)