在SQL中按日期和数量排名

时间:2018-02-13 05:51:28

标签: sql rank sales

我有一张名为SALES的表,包括Person,Dates和Qty。

Person  Date       Qty
Jim     2016-08-01  1
Jim     2016-08-02  3
Jim     2016-08-03  1
Bob     2016-08-01  5
Bob     2016-08-02  1
Bob     2016-08-03  6
Sheila  2016-08-01  4
Sheila  2016-08-02  0
Sheila  2016-08-03  2

我希望按每个日期排序数量,输出如下:

Person  Date       Qty    Rank
Bob     2016-08-01  5      1
Sheila  2016-08-01  4      2
Jim     2016-08-01  1      3
Jim     2016-08-02  3      1
Bob     2016-08-02  1      2
Sheila  2016-08-02  0      3
Bob     2016-08-03  6      1
Sheila  2016-08-03  2      2
Jim     2016-08-03  1      3

如何在此处使用排名功能?

1 个答案:

答案 0 :(得分:0)

试试这个

DECLARE @SALES TABLE(
Person NVARCHAR(50),
[Date] NVARCHAR(50),
Qty INT
)

INSERT INTO @SALES VALUES('Jim','2016-08-01',1)
INSERT INTO @SALES VALUES('Jim','2016-08-02',3)
INSERT INTO @SALES VALUES('Jim','2016-08-03',1)
INSERT INTO @SALES VALUES('Bob','2016-08-01',5)
INSERT INTO @SALES VALUES('Bob','2016-08-02',1)
INSERT INTO @SALES VALUES('Bob','2016-08-03',6)
INSERT INTO @SALES VALUES('Sheila','2016-08-01',4)
INSERT INTO @SALES VALUES('Sheila','2016-08-02',0)
INSERT INTO @SALES VALUES('Sheila','2016-08-03',2)



SELECT * ,
ROW_NUMBER() OVER( PARTITION BY [Date] 
ORDER BY Qty DESC) N'Rank' 
FROM @SALES 
GROUP BY [Date], Person, Qty
ORDER BY [Date] ASC,Qty DESC

结果
enter image description here

==============================================
更新:每天选择前2名

SELECT * 
FROM(
    SELECT * ,
    ROW_NUMBER() OVER( PARTITION BY [Date] 
    ORDER BY Qty DESC) N'Rank' 
    FROM @SALES 
    GROUP BY [Date], Person, Qty
    ) AS NewTable
WHERE NewTable.Rank  < 3

结果
enter image description here
注:
您无法直接使用WHERE Rank < 3,因为WHERE子句在SELECT语句之前,WHERE子句无法识别Rank列。你必须使用子查询。