从列中选择具有唯一值的行

时间:2013-07-16 04:18:50

标签: sql-server-2008

我想选择按日期排序的前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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 with Demo