Select 来自不同类别的前 n 个

Select top n from different categories

所以我想 select 每年每季度销量最高的 10 种产品。季度是一年的 1/4。 示例:

年份->2017 第一季度:销量前 10 的产品

我想要这样的输出:(其中 key->ProductKey,ProductVolume->Count of sales of that product,Quarter->Qumber of the quarter,Year->Year in question.

|关键字|产品数量|季度|年份| ………… ....

第二季度:销量前 10 的产品 ... 年份->2016 第一季度:Top 10 畅销产品 第二季度:销量前 10 的产品

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

这是我现在得到的结果,所有的结果...

enter image description here

上图表示此查询的结果,即我在内部联接中使用的表的布局。

Select top 1 * from Product;
  Select top 1 * from Sales;
  Select top 1 * from SalesProduct;

按每个产品每季度+年的销售额排序。

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