如何从不同的表中检索最小值

时间:2013-01-11 16:27:03

标签: sql

我想从table1table2中检索(time1)的最小值,例如

table 1(id, time1, time2, time3)
table2(id, time1,time2,time3) 
id , time 1, time2, time3 (after union)
1, 2:00pm,1:30pm,1:31pm
1,1:45pm, 3:00pm,4:00pm
2,2:01pm,1:31pm,1:32pm
2,1:50pm, 3:01pm,4:00pm

我想要的最终结果是

id, time 1, time2, time3 
1,1:45pm, 3:00pm,4:00pm
2,1:50pm, 3:01pm,4:00pm

我尝试了如下,但我得到了重复的ID,它是table1和table2的min(time1)值。如何从联合结果获得min(time1)行,如上例所示?

SELECT id,time1,time2,time3 FROM
Table1
WHERE time1 =
(
SELECT Min(time1)
FROM Table1
)
UNION
SELECT id,time1,time2,time3 FROM
Table2
WHERE time1 =
(
SELECT Min(time1)
FROM Table2
)

非常感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您可以union将这些表放在一起,然后按id分组:

select  id
,       min(time1) as min_time1
,       min(time2) as min_time2
,       min(time3) as min_time3
from    (
        select  id
        ,       time1
        ,       time2
        ,       time3
        from    table1
        union all
        select  id
        ,       time1
        ,       time2
        ,       time3
        from    table2
        ) as SubQueryAlias
group by
        id