因此,我想选择每年每季度销售量最高的10种产品。季度为一年的1/4。 例如:
年-> 2017 第一季度:销售量排名前十的产品
我想要这种输出:(其中键-> ProductKey,ProductVolume->该产品的销售数量,季度->所讨论的季度数,年份->所讨论的年份。
|键|产品数量|季度|年份| ....... ....
第二季度:十大畅销产品 ... 年份-> 2016 第一季度:售出的十大产品 第二季度:销量最高的十大产品
SELECT s.ProductKey as [Key],
COUNT(s.ProductKey) as [ProductVolume],
datepart(q, s.OrderDate) as [Quarter],(yyyy, s.OrderDate) as [Year]
FROM (Select p.ProductKey,
s.OrderDate,
row_number() over(PARTITION BY datepart(q, s.OrderDate)
order by
p.ProductKey desc) as rn
FROM Sales as s
INNER JOIN SalesProduct as sp
ON sp.SalesKey=s.SalesKey
INNER JOIN Product as p
ON p.ProductKey=sp.ProductKey
) as s
WHERE datepart(yyyy, s.OrderDate)
BETWEEN YEAR(getdate())-2 AND YEAR(getdate())
GROUP BY datepart(q, s.OrderDate), datepart(yyyy, s.OrderDate), s.ProductKey
这是我现在获得的结果,所有结果...
上面的图像表示此查询的结果,即我在内部联接中使用的表的布局。
Select top 1 * from Product;
Select top 1 * from Sales;
Select top 1 * from SalesProduct;
答案 0 :(得分:0)
按每季度+年每种产品的销售价值排序。
DECLARE @Sales TABLE (
SalesKey INT,
OrderDate DATETIME
)
DECLARE @SalesProduct TABLE (
SalesKey INT,
ProductKey INT,
UnitPrice MONEY,
OrderQuantity TINYINT
)
INSERT INTO @Sales(SalesKey,OrderDate) SELECT 1, '2018-05-18'
INSERT INTO @Sales(SalesKey,OrderDate) SELECT 2, '2018-05-18'
INSERT INTO @SalesProduct(SalesKey,ProductKey,UnitPrice,OrderQuantity) SELECT 1,123,3.50,1
INSERT INTO @SalesProduct(SalesKey,ProductKey,UnitPrice,OrderQuantity) SELECT 1,125,3.50,1
INSERT INTO @SalesProduct(SalesKey,ProductKey,UnitPrice,OrderQuantity) SELECT 2,123,2.50,5
SELECT *
FROM (
Select
datepart(year, s.OrderDate) AS [Year],
datepart(q, s.OrderDate) AS [Quarter],
sp.ProductKey,
sum(sp.OrderQuantity) AS [TotalOrdered],
sum(sp.UnitPrice * sp.OrderQuantity) AS [TotalValue],
row_number() over(PARTITION BY datepart(year, s.OrderDate),datepart(q, s.OrderDate) order by sum(sp.OrderQuantity) desc) as [Row]
FROM @Sales as s
INNER JOIN @SalesProduct as sp ON sp.SalesKey=s.SalesKey
WHERE datepart(yyyy, s.OrderDate) BETWEEN YEAR(getdate())-2 AND YEAR(getdate())
GROUP BY datepart(year, s.OrderDate),datepart(q, s.OrderDate),sp.ProductKey
) dat
WHERE dat.[Row]<=10