获取每个ID的最新日期

时间:2018-01-24 09:00:18

标签: sql sql-server

我需要获取此表中每个ID的最大日期

ID       Date
___      ____
1     2017-01-01
1     2017-03-01
2     2018-01-01
2     2013-07-03
2     2015-03-02
3     2011-11-11

所以我想要这样的东西返回

ID       Date
___      ____
1     2017-03-01
2     2018-01-01
3     2011-11-11

提前致谢

2 个答案:

答案 0 :(得分:3)

select ID, Max(Date) as Date 
from yourtable
group by ID

答案 1 :(得分:1)

使用ROW_NUMBER

SELECT ID, Date
FROM
(
    SELECT ID, Date, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Date DESC) rn
    FROM yourTable
) t
WHERE rn = 1;

GROUP BY

SELECT ID, MAX(Date) AS Date
FROM yourTable
GROUP BY ID;