如何按最大日期显示行

时间:2013-02-26 04:19:19

标签: sql sql-server tsql sql-server-2005

使用SQL Server 2005

表1

ID Date Value

001 23/01/2012 100
002 24/02/2012 200
002 21/01/2012 300
003 18/02/2012 200
003 19/02/2012 100
...

我想为每个id显示max(date)。怎么做。

我试过

Select id, max(date), value from table group by id, value

但输出显示所有行

预期输出

ID Date Value

001 23/01/2012 100
002 24/02/2012 200
003 19/02/2012 100
...

需要SQL查询帮助

4 个答案:

答案 0 :(得分:1)

使用Rank over:

select id,
date, value from (
select id,
date, value,
Rank() over (Partition BY ID order by date DESC) rank
from Table1) a
where a.rank = 1

答案 1 :(得分:0)

with CTE as 
(
Select Id, MAX(Date) as maxdate
from table1 
Group by Id
)
Select t1.ID, t1.Maxdate, t2.Value
from CTE t1, Table1 t2
where t1.ID = t2.ID
and t1.maxdate = t2.date;

Demo sqlfiddle

答案 2 :(得分:0)

尝试类似

的内容
SELECT id, date, value 
FROM table1, (SELECT id, max(date) FROM table1 GROUP BY id) t
WHERE table1.id =t.id AND table1.date=t.date 

答案 3 :(得分:0)

选项CTE + RANK()功能

;WITH cte AS
(
 SELECT id, date, value,
        RANK() OVER (PARTITION BY ID ORDER BY date DESC) AS rn
 FROM Table1
 )
 SELECT *
 FROM cte
 WHERE rn = 1

SQLFiddle上的演示

EXISTS运算符选项

SELECT t1.id, t1.date, t1.value
FROM Table1 t1
WHERE EXISTS(
             SELECT 1
             FROM Table1 t2
             WHERE t1.id = t2.id
             HAVING MAX(t2.date) = t1.date
             )

SQLFiddle上的演示

APPLY运算符选项

SELECT t1.id, t1.date, t1.value
FROM Table1 t1 CROSS APPLY (
                            SELECT 1 AS 'IsMatch'
                            FROM Table1 t2
                            WHERE t1.id = t2.id
                            HAVING MAX(t2.date) = t1.date
                            ) o

SQLFiddle上的演示