SQL是否可以从另一个表的MAX列进行ORDER BY?

时间:2012-07-19 14:17:43

标签: sql db2 sql-order-by

T1:
ID   
100
101
102

T2:
ID     OWNDATE   
100    1.1.2001
100    3.1.2001
101    2.1.2001
102    4.1.2001

我想要select * from T1之类的东西,但是从T2表中按照MAX自己的日期列排序?

结果将是

102
100
101

这可能吗? 感谢

抱歉

1 个答案:

答案 0 :(得分:3)

只需在ID上加入两个表,然后按OWNDATE排序。

SELECT T1.* 
FROM T1 
INNER JOIN T2 on T1.[ID] = T2.[ID]
ORDER BY T2.OWNDATE

<强>更新:

SELECT T1.* FROM T1
INNER JOIN (
    SELECT [ID], MAX(OWNDATE) AS OWNDATE
    FROM T2
    GROUP BY [ID]
) T2 ON T1.[ID] = T2.[ID]
ORDER BY OWNDATE DESC