4

我有一张表,它的数据如下所示:

 id         name       date
 ---------  ---------  ----------
 1          a          2012-08-30 10:36:27.393
 1          b          2012-08-30 14:36:27.393
 2          c          2012-08-30 13:36:27.393
 2          d          2012-08-30 16:36:27.393

我用这个查询检索最大日期时间:

SELECT id,Max(date) as mymaxdate
FROM table1
group by id

这个查询给了我这样的两行:

1     2012-08-30 14:36:27.393
2     2012-08-30 16:36:27.393

这是正确的,但我怎样才能改变它来检索这个结果?

1   b  2012-08-30 14:36:27.393
2   d  2012-08-30 16:36:27.393

谢谢

4

2 回答 2

8

对于 SQL Server 2005+

WITH cteMaxDate AS (
    SELECT id, name, date, 
           ROW_NUMBER() OVER(PARTITION BY id ORDER BY date DESC) AS RowNum
        FROM table1
)
SELECT id, name, date
    FROM cteMaxDate
    WHERE RowNum = 1;
于 2012-08-30T16:32:23.377 回答
2

选项之一:

select 
    t1.id
    ,t1.name
    ,t1.date 
from 
    table1 t1
    inner join (
        SELECT id,Max(date) as mymaxdate
        FROM table1
        group by id
    ) mt1
        on t1.id = mt1.id
        and t1.date = mt1.mymaxdate
于 2012-08-30T16:30:13.923 回答