2013-06-05 2023 views
3

我必須從日期列和組中選擇最近日期和最後一個日期列ID列。從SQL Server 2005的日期列中選擇最近日期和最後一個日期

這樣我就可以得到最新的日期和最後一個特定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 
+3

不匹配:標題說,2005年的標籤說2008 R2 ... –

+1

另外:SQL服務器** 2005 **(如標題所述)沒有'DATE'數據類型....(只有'DATETIME') –

回答

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 
0

注:訴諸與UNION插入所有的SQL服務器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; 
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 
       )