我想有一种更好的方法可以从row_number
中获取最后一行,而不是使用T-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
答案 0 :(得分:4)
是的,您可以使用:
SELECT
PERSON_ID,
MAX(ORDER_DATE) AS ORDER_DATE,
COUNT(*) AS ORDER_CNT
FROM @T
GROUP BY PERSON_ID
答案 1 :(得分: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;