1

使用 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

4 回答 4

1

使用排名:

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
于 2013-02-26T04:33:22.560 回答
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;

演示 sqlfiddle

于 2013-02-26T04:30:44.570 回答
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 
于 2013-02-26T04:43:06.933 回答
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上的演示

于 2013-02-26T08:02:10.513 回答