2016-08-30 154 views
0

我想有一種更好的方法可以從row_number中獲取最後一行,而不是使用T-SQL進行多重嵌套。使用SQL獲取ROW_NUMBER中的最後一行使用SQL

我需要訂單總數和最後訂購日期。說我有以下幾點:

DECLARE @T TABLE (PERSON_ID INT, ORDER_DATE DATE) 
INSERT INTO @T VALUES(1, '2016/01/01') 
INSERT INTO @T VALUES(1, '2016/01/02') 
INSERT INTO @T VALUES(1, '2016/01/03') 
INSERT INTO @T VALUES(2, '2016/01/01') 
INSERT INTO @T VALUES(2, '2016/01/02') 
INSERT INTO @T VALUES(3, '2016/01/01') 
INSERT INTO @T VALUES(3, '2016/01/02') 
INSERT INTO @T VALUES(3, '2016/01/03') 
INSERT INTO @T VALUES(3, '2016/01/04') 

我要的是:

PERSON_ID ORDER_DATE ORDER_CNT 
1   2016-01-03 3 
2   2016-01-02 2 
3   2016-01-04 4 

有沒有更好的方式來做到這一點,除了以下:

SELECT * 
    FROM (
    SELECT * 
     , ROW_NUMBER() OVER (PARTITION BY PERSON_ID ORDER BY ORDER_CNT DESC) AS LAST_ROW 
     FROM (
     SELECT * 
      , ROW_NUMBER() OVER (PARTITION BY PERSON_ID ORDER BY ORDER_DATE) AS ORDER_CNT 
      FROM @T 
     ) AS A 
    ) AS B 
WHERE LAST_ROW = 1 

回答

4

是的,你可以使用這個:

SELECT 
    PERSON_ID, 
    MAX(ORDER_DATE) AS ORDER_DATE, 
    COUNT(*) AS ORDER_CNT 
FROM @T 
GROUP BY PERSON_ID 
2
SELECT a.PERSON_ID 
    , a.ORDER_DATE 
    , a.ORDER_CNT 
FROM 
    (
    SELECT PERSON_ID 
     , ORDER_DATE 
     , rn = ROW_NUMBER() OVER (PARTITION BY PERSON_ID ORDER BY ORDER_DATE DESC) 
     , ORDER_CNT = COUNT(ORDER_DATE) OVER (PARTITION BY PERSON_ID) 
    FROM @T 
    ) AS a 
WHERE rn = 1 
ORDER BY a.PERSON_ID;