用窗口函数计算销售额

时间:2017-04-28 10:18:11

标签: sql sql-server sql-server-2008

我有这个问题:

USE AdventureWorks2012;
GO
SELECT CustomerID,COUNT(*) AS CountOfSales,
COUNT(CustomerID) OVER (PARTITION BY CountOfSales) Total,

RANK() OVER(ORDER BY COUNT(*) DESC) AS Ranking,
ROW_NUMBER() OVER(ORDER BY COUNT(CustomerID) DESC) AS Row,
DENSE_RANK() OVER(ORDER BY COUNT(*)) AS DenseRanking
FROM Sales.SalesOrderHeader
GROUP BY CustomerID
ORDER BY COUNT(*) DESC;

并给出了这个结果:

CustomerID  CountOfSales    Total   Ranking Row DenseRanking
11091   28  1   1   2   17
11176   28  1   1   1   17
11200   27  1   3   9   16
11331   27  1   3   12  16
11287   27  1   3   5   16
11262   27  1   3   8   16
11276   27  1   3   11  16
11330   27  1   3   6   16
11711   27  1   3   13  16
11277   27  1   3   3   16

但是现在我想要一个像total countOfSales这样的列,所以:有2个28和11个27

所以我的问题是如何管理它?

谢谢

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,您可以将查询包装到子查询中并使用PARTITION BY执行COUNT(*):

SELECT *, COUNT(*) OVER (PARTITION BY CountOfSales) AS total_countOfSales
FROM (
SELECT CustomerID,COUNT(*) AS CountOfSales,
COUNT(CustomerID) OVER (PARTITION BY CountOfSales) Total,

RANK() OVER(ORDER BY COUNT(*) DESC) AS Ranking,
ROW_NUMBER() OVER(ORDER BY COUNT(CustomerID) DESC) AS Row,
DENSE_RANK() OVER(ORDER BY COUNT(*)) AS DenseRanking
FROM Sales.SalesOrderHeader
GROUP BY CustomerID
) a