SQL Server按日期获取最新值

时间:2017-09-13 17:24:22

标签: sql sql-server database

我有一个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

5 个答案:

答案 0 :(得分:6)

top with tiesrow_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 |
+------------+-------------+----------------------------+

答案 1 :(得分:1)

此查询将为您提供每个项目的最新日期

Select Project_Id, Max (Update_Date) Max_Update_Date
From MyTable
Group By Project_Id

所以将它加入原始表

Select Project_Id, Update_Date, Update_Text
From MyTable
Inner Join
(
    Select Project_Id, Max (Update_Date) Max_Update_Date
    From MyTable
    Group By Project_Id
) MaxDates
On MyTable.Project_Id = MaxDates.Project_Id
And MyTable.Update_Date = MaxDates.Max_Update_Date

答案 2 :(得分:1)

您可以找到MAX(date)之类的:

SELECT * FROM [table] 
INNER JOIN (SELECT project_id, date = MAX(update_date) FROM [table] GROUP BY project_id) AS a
ON [table].project_id = a.project_id AND update_date = date

或者您可以使用ROW_NUMBER()之类的:

SELECT * FROM (
SELECT *, rownum = ROW_NUMBER() OVER (PARTITION BY project_id ORDER BY 
update_date DESC) FROM [table]
) AS a WHERE rownum = 1

答案 3 :(得分:0)

你可以这样做:

{{1}}

<强> Demo

答案 4 :(得分:0)

注意最重要的答案

尽管有人可能会说这是最好的答案,但通常不是最有效的查询时间。在我的数据中,以下示例要快一个数量级。

SELECT project_id, update_date, update_text FROM projects P WHERE update_date = (SELECT MAX(update_date) FROM projects WHERE project_id = P.project_id)

(如果在给定日期可以进行多个更新,则需要在update_text和group by上使用max,如在此特定示例中一样,您将不知道哪个update_text值有效。)