3

我必须从日期列中选择最新日期和最后一个日期并按列分组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
4

4 回答 4

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
于 2013-06-05T06:16:38.143 回答
0

注意:对 sql-server-2005 使用 UNION ALL 进行 INSERT。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;
于 2013-06-05T07:22:22.790 回答
0

请查看SQL Server 2005 / SQL Server 2008 的MSDN 解决方案。

于 2013-06-05T08:49:39.987 回答
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
                ) 
于 2013-06-05T08:24:32.057 回答