2017-09-13 135 views
2

得到最新值我已經PROJECT_ID INT,UPDATE_DATE日期時間,UPDATE_TEXT VARCHAR(最大值)SQL Server將日期

表有每PROJECT_ID許多更新SQL Server表。我需要通過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 

回答

4

使用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 | 
+------------+-------------+----------------------------+ 
+0

打我吧!這是正確的答案。通過project_id進行分區和按日期排序desc是回答這種多重身份驗證/審覈類型數據的最佳方法。 – Simon

0

你可以做到這一點是:

with CTE as(
SELECT project_id, MAX(update_date) update_date 
FROM YourTable 
GROUP BY project_id 
    ) 

SELECT cte.project_id, cte.update_date , max(t.update_text) update_text 
FROM YourTable T inner join CTE on T.project_id = CTE.project_id 
group by cte.project_id, cte.update_date ; 

Demo

+0

這將會給你一個錯誤,你有'MAX(UPDATE_DATE)'和' GROUP BY project_id'但是'update_text'缺少聚合。 – Simon

+0

@Simon是的,我會修復答謝謝你。 – Sami

+0

@Simon現在完成了! – Sami

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 
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