1

我有一张桌子:

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 中仅选择最大日期?

4

2 回答 2

2
select cod_pr,MAX(Date) from Table
group by cod_pr
于 2012-12-12T11:12:38.177 回答
1

如果您想要所有列,您可以ROW_NUMBER在 CTE 中使用:

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
于 2012-12-12T11:11:11.830 回答