SQL: how to select single record for multiple id's on the basis of max datetime?

丶灬走出姿态 提交于 2019-12-06 02:05:29

问题


I have the following SQL table,

Id      WindSpeed      DateTime
--------------------------------------
1       1.1            2009-09-14 16:11:38.383
1       1.9            2009-09-15 16:11:38.383
1       2.0            2009-09-16 16:11:38.383
1       1.8            2009-09-17 16:11:38.383
1       1.7            2009-09-19 16:11:38.382
2       1.9            2009-09-19 16:11:38.383
1       1.6            2009-09-19 16:11:38.383
2       1.2            2009-09-20 16:11:38.383

I want to write a query which will return me the following result set from the above table:

Id      WindSpeed      DateTime
--------------------------------------
1       1.6            2009-09-19 16:11:38.383
2       1.2            2009-09-20 16:11:38.383

The above reuslt contains the latest (on the basis of latest datetime for that id) single entry. Which means I have multiple record id's with datetime.

I want to get the latest single entry of all id's.


回答1:


SELECT        a.Id, a.WindSpeed, a.DateTime
FROM          YourTable AS a
INNER JOIN     
(
    SELECT    ID, Max(DateTime) AS DateTime
    FROM      YourTable
    GROUP BY  ID
) AS b
ON            a.ID = b.ID
AND           a.DateTime = b.DateTime



回答2:


SELECT t1.Id, t1.WindSpeed, t1.DateTime
  FROM table1 As t1
 WHERE t1.DateTime = (SELECT Max(DateTime)
                       FROM table1 As t2
                      WHERE t2.ID = t1.ID)



回答3:


This should also do what you want:

SELECT ID, WindSpeed, [DateTime] 
FROM (
    SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY [DateTime] DESC) AS RowNumber,
        Id, WindSpeed, [DateTime]
    FROM MyTable
) T
WHERE RowNumber = 1


来源:https://stackoverflow.com/questions/1594092/sql-how-to-select-single-record-for-multiple-ids-on-the-basis-of-max-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!