Sql 列出每年最畅销的三种产品
问题是列出每年最畅销的三种产品 我执行了以下查询Sql 列出每年最畅销的三种产品,sql,sql-server,greatest-n-per-group,Sql,Sql Server,Greatest N Per Group,问题是列出每年最畅销的三种产品 我执行了以下查询 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.ProductKe
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年的数据,为什么不是所有的年份?一般的想法可能是在每组行1、2、3中添加一个列计数器。。。然后选择计数器小于或等于3的记录使用下面的查询
; 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条记录作为输出。不能是[mySQL]。MySQL不使用TOP n语法。您确定标记正确吗?选择前三名不是mysql。2006年公路自行车很热门。我不确定你是否可以使用top关键字。如果可以,则查询结果是正确的,因为它只提供3条记录。这样,您就不能为每个组呼叫3条记录!让我们换一种方式试试它的SQL server不是我的SqlThank unnikrishnan R,因为我是新手,这个答案对我很有用,你能告诉我如何以及何时需要使用CTE函数吗?简单地说,我们可以说CTE将充当一个临时表,其中包含一个结果集,我们可以应用过滤器或标准,ie我们可以使用结果集进行进一步计算,但我们也可以使用CTE进行递归查询。。您可以通过此链接了解有关递归cte的更多信息