0

我想选择按日期排序的前 3 条记录,以便这些记录没有相同的 ID,对于两个(或更多)相同 ID 的记录,请选择最新的记录。表是这样的:

ID  | Date                 | Value
1   | 2013-04-29T16:27:20  | value1
2   | 2013-04-29T19:46:25  | value2
2   | 2013-04-30T16:50:30  | value3
3   | 2013-04-30T16:40:30  | value4
1   | 2013-04-30T17:50:30  | value5

我希望结果是这样的:

ID  | Date                 | Value
1   | 2013-04-30T17:50:30  | value5
2   | 2013-04-30T16:50:30  | value3
3   | 2013-04-30T16:40:30  | value4
4

2 回答 2

0
SELECT t.ID, t.Date, t.Value
FROM (
    SELECT ID, Date, Value, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Date DESC) AS RowNumber
    FROM table_name
) t
WHERE t.RowNumber = 1
于 2013-07-16T04:22:05.527 回答
0

由于您使用的是 SQL Server 2005+,因此您可以实施row_number()以获得结果:

select id, date, value
from 
(
  select id, date, value,
    row_number() over(partition by id order by date desc) seq
  from yourtable
) d
where seq = 1;

请参阅SQL Fiddle with Demo

或者,您可以使用带有聚合函数的子查询来返回id最新日期:

select t1.id, t1.date, t1.value
from yourtable t1
inner join
(
  select id, max(date) date
  from yourtable
  group by id
) t2
  on t1.id = t2.id
  and t1.date = t2.date

请参阅带有演示的 SQL Fiddle

于 2013-07-16T04:22:54.600 回答