我必须在ID
列的日期列和分组中选择最新日期和最后一个日期。
这样我就可以获得特定ID的最新日期和最后一个日期。
假设,
-----------------------------
ID Date
-----------------------------
AA 5/5/2012
AA 6/5/2012
BB 19/5/2012
BB 20/5/2012
BB 18/5/2012
BB 17/5/2012
CC 8/5/2012
CC 19/5/2012
CC 20/5/2012
必需的输出
-----------------------------
ID Date
-----------------------------
AA 6/5/2012
AA 5/5/2012
BB 20/5/2012
BB 19/5/2012
CC 20/5/2012
CC 19/5/2012
答案 0 :(得分:2)
简单使用ROW_NUMBER
:
;WITH OrderedRows as (
SELECT ID,Date,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Date desc) rn
from Table
)
select * from OrderedRows where rn <=2
答案 1 :(得分:0)
注意:使用UNION ALL INSAL for sql-server-2005。 sql-server-2008 +将使用多值列表。
CREATE TABLE #dates(
id CHAR(2) NOT NULL,
dt DATE NOT NULL
);
INSERT INTO #dates(
id,
dt
)
SELECT
'AA','2012-05-05'
UNION ALL
SELECT
'AA','2012-05-06'
UNION ALL
SELECT
'BB','2012-05-19'
UNION ALL
SELECT
'BB','2012-05-20'
UNION ALL
SELECT
'BB','2012-05-18'
UNION ALL
SELECT
'BB','2012-05-17'
UNION ALL
SELECT
'CC','2012-05-08'
UNION ALL
SELECT
'CC','2012-05-19'
UNION ALL
SELECT
'CC','2012-05-20';
SELECT
id,
dt,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY dt DESC) AS seq_id
INTO
#dates_seq
FROM
#dates;
SELECT
id,
dt
FROM
#dates_seq
WHERE
seq_id<=2
ORDER BY
id,
dt DESC;
DROP TABLE #dates_seq;
DROP TABLE #dates;
答案 2 :(得分:0)
还有一个选择
SELECT *
FROM Table5 t
WHERE t.Date IN(
SELECT TOP 2 t2.Date
FROM Table5 t2
WHERE t.ID = t2.ID
ORDER BY t2.Date DESC
)
答案 3 :(得分:0)
请检查MSDN solution是否有SQL Server 2005 / SQL Server 2008。