【问题标题】:List the top 3 selling product for every year列出每年销量前三的产品
【发布时间】:2016-09-03 19:14:25
【问题描述】:

问题是“列出每年销量前三的产品”

我执行了以下查询

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 年”的数据,为什么不是所有年份?

【问题讨论】:

  • 不能是 [mySQL]。 MySQL 不使用TOP n 语法。
  • 您确定您的标签正确吗? select top 3不是mysql语法
  • 公路自行车在 2006 年很火。
  • 我不确定你是否可以使用 top 关键字。如果可以,那么查询的结果是正确的,因为它只给你 3 条记录。这样一来,您就不能为每个组大喊 3 条记录!让我们尝试另一种方式
  • 它的 SQL 服务器不是我的 sql

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


【解决方案1】:

使用下面的查询..

   ; 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

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

【讨论】:

  • 感谢 unnikrishnan R,因为我是新手,这个答案对我来说非常有用,你能告诉我如何以及何时需要使用 CTE 函数吗??
  • 简单来说,我们可以说CTE将充当一个临时表,其中包含我们可以应用过滤器或标准的结果集,即我们可以使用结果集进行进一步计算。但是我们也可以使用 CTE 进行递归查询。你可以在这个链接上了解更多关于递归 cte 的信息link
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    相关资源
    最近更新 更多