SQL中前N的总和

时间:2018-02-13 12:44:08

标签: sql ranking totals

我有一个包含人物,日期和数量的SALES表:

SYSENTER

我可以使用以下代码按日期排名前2:

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

我的两个问题是:

1)我怎样才能看到每个日期前2名的总数量,例如:

/****** Top 2 Salespersons  ******/
SELECT * 
FROM(
    SELECT * ,
    ROW_NUMBER() OVER( PARTITION BY [Date] 
    ORDER BY Qty DESC) N'Rank' 
    FROM [Coinmarketcap].[dbo].[sales]
    GROUP BY [Date], Person, Qty
    ) AS NewTable
WHERE NewTable.Rank  < 3

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

2)我如何获得不同排名组的每天总数量,例如:

Date       Total Qty
2016-08-01    6
2016-08-02    5
2016-08-03    8

1 个答案:

答案 0 :(得分:0)

首先:

SELECT NewTable.Date, Sum(NewTable.Qty) 
FROM(
    SELECT * ,
    ROW_NUMBER() OVER( PARTITION BY [Date] 
    ORDER BY Qty DESC) N'Rank' 
    FROM [Coinmarketcap].[dbo].[sales]
    GROUP BY [Date], Person, Qty
    ) AS NewTable
WHERE NewTable.Rank  < 3
group by NewTable.Date

第二次试试这个:

SELECT NewTable.Date, 
       Trunc((NewTable.Rank - 1) / 2) * 2 + 1, -- lower rank
       Trunc((NewTable.Rank - 1) / 2) * 2 + 2, -- upper rank
       Sum(NewTable.Qty) 
FROM(
    SELECT * ,
    ROW_NUMBER() OVER( PARTITION BY [Date] 
    ORDER BY Qty DESC) N'Rank' 
    FROM [Coinmarketcap].[dbo].[sales]
    GROUP BY [Date], Person, Qty
    ) AS NewTable
group by NewTable.Date, 
         Trunc((NewTable.Rank - 1) / 2) * 2 + 1,
         Trunc((NewTable.Rank - 1) / 2) * 2 + 2