列出每年最畅销的3款产品

时间:2016-09-03 19:14:25

标签: sql sql-server greatest-n-per-group

问题是“列出每年最畅销的3种产品”

我执行了以下查询

select top 3 b.CalendarYear,c.ProductKey, d.EnglishProductSubcategoryName ,SUM(a.SalesAmount) as SALES
from FactInternetSales as A inner join dimdate as B
on a.OrderDateKey =b.DateKey
inner join DimProduct as c
on c.ProductKey = a.ProductKey
inner join DimProductSubcategory as d
on c.ProductSubcategoryKey = d.ProductSubcategoryKey
inner join  DimProductCategory as e 
on d.ProductCategoryKey=e.ProductCategoryKey
group by b.CalendarYear,c.ProductKey, d.EnglishProductSubcategoryName
order by SALES desc

我得到了以下答案

CalendarYear    ProductKey  EnglishProductSubcategoryName    SALES
2006    312 Road Bikes  658401.68
2006    313 Road Bikes  608305.90
2006    310 Road Bikes  608305.90

我的疑问是,为什么不是所有年份只有“2006年”数据才会出现?

2 个答案:

答案 0 :(得分:2)

使用以下查询..

   ; WITH cte_1
     AS
     ( SELECT CalendarYear,ProductKey
                      ,EnglishProductSubcategoryName,SALES
                     ,ROW_NUMBER() OVER(PARTITION BY
                           CalendarYear,ProductKey
                          ,EnglishProductSubcategoryName
                       ORDER BY Sales DESC) RNO
         FROM (select b.CalendarYear,c.ProductKey
                                ,d.EnglishProductSubcategoryName
                                ,SUM(a.SalesAmount) as SALES
                       from FactInternetSales as A 
                           inner join dimdate as B
                                 on a.OrderDateKey =b.DateKey
                           inner join DimProduct as c
                                on c.ProductKey = a.ProductKey
                           inner join DimProductSubcategory as d
                                on c.ProductSubcategoryKey = d.ProductSubcategoryKey
                           inner join  DimProductCategory as e 
                                on d.ProductCategoryKey=e.ProductCategoryKey
                        group by b.CalendarYear,c.ProductKey
                          ,  d.EnglishProductSubcategoryName)t
  )
   SELECT CalendarYear,ProductKey
                      ,EnglishProductSubcategoryName,SALES
    FROM cte_1
    WHERE RNO<4
    ORDER BY CalendarYear DESC,RNO ASC

在提供的脚本中,您只选择结果集中的top3记录。因此,您将获得3条记录作为输出。

答案 1 :(得分:0)

一般的想法可能是为每组行添加一个列计数器(1 2 3 ...),然后选择计数器小于或等于3的记录