1

SQLServer2005の使用

表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

次のようなものを試してください

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

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 に答える