我有一个 SQL Server 表,其中包含 project_id int、update_date datetime、update_text varchar(max)
表中每个 project_id 都有很多更新。我需要通过 update_date 为所有 project_id 值获取最新的。
例子:
project_id update_date update_text 1 2017/01/01 Happy new year. 2 2017/01/01 Nice update 2 2017/02/14 Happy Valentine's 3 2016/12/25 Merry Christmas 3 2017/01/01 A New year is a good thing
查询应该得到:
project_id update_date update_text 1 2017/01/01 Happy new year. 2 2017/02/14 Happy Valentine's 3 2017/01/01 A New year is a good thing
最佳答案
使用 top with ties
与 row_number()
select top 1 with ties
project_id, update_date, update_text
from projects
order by row_number() over (partition by project_id order by update_date desc)
rextester 演示:http://rextester.com/MGUNU86353
返回:
+------------+-------------+----------------------------+
| project_id | update_date | update_text |
+------------+-------------+----------------------------+
| 1 | 2017-01-01 | Happy new year. |
| 2 | 2017-02-14 | Happy Valentine's |
| 3 | 2017-01-01 | A New year is a good thing |
+------------+-------------+----------------------------+
关于SQL Server 按日期获取最新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46203506/