我有一张桌子:
id cod_pr Date nr
-------------------------------
1 22 12.10.2012 2
2 25 12.10.2012 3
3 22 12.11.2012 5
4 25 12.11.2012 2
5 22 12.12.2012 4
6 23 12.10.2012 3
如何从每个cod_pr中仅选择最大日期?
答案 0 :(得分:2)
select cod_pr,MAX(Date) from Table
group by cod_pr
答案 1 :(得分:1)
如果您想要所有列,可以在CTE中使用ROW_NUMBER
:
WITH CTE AS
(
SELECT id,cod_pr,Date,nr,
ROW_NUMBER() OVER (PARTITION BY cod_pr ORDER BY Date DESC) AS RN
FROM dbo.Table
)
SELECT id,cod_pr,Date,nr, FROM CTE WHERE RN = 1
否则您只需使用GROUP BY
SELECT cod_pr, MAX(Date) AS MaxDate
FROM dbo.Table
GROUP BY cod_pr