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