6

我有以下 SQL 表,

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

我想编写一个查询,它将从上表中返回以下结果集:

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

上面的 reuslt 包含最新的(基于该 id 的最新日期时间)单个条目。这意味着我有多个带有日期时间的记录 ID。

我想获取所有 id 的最新单个条目。

4

3 回答 3

11
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
于 2009-10-20T12:04:02.043 回答
5
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)
于 2009-10-20T12:09:33.500 回答
2

这也应该做你想要的:

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
于 2009-10-20T12:52:29.680 回答