栈!我的一个查询有一个小问题。我有一个SQL查询,它显示了我最受欢迎的产品类别列表。它看起来像这样:
SELECT CategoryName, SUM(Quantity) as TotalQuantity
FROM ([Order Details]
INNER JOIN Products ON [Order Details].ProductID = Products.ProductID
INNER JOIN Categories ON Products.ProductID = Categories.CategoryID)
GROUP BY CategoryName
ORDER BY SUM(Quantity) DESC;
现在,我需要修改它,因此它会显示每个连续年份的类别列表。它应涵盖199-1998年。我不想分别对每年的查询进行查询。有没有办法更改此查询以显示每年的类别列表?
答案 0 :(得分:3)
SELECT CategoryName,datepart(yyyy, [YoutDateCol]) [date], SUM(Quantity) as TotalQuantity
FROM ([Order Details]
INNER JOIN Products ON [Order Details].ProductID = Products.ProductID
INNER JOIN Categories ON Products.ProductID = Categories.CategoryID)
GROUP BY CategoryName,datepart(yyyy, [YoutDateCol])
ORDER BY SUM(Quantity) DESC;
答案 1 :(得分:2)
这应该适合你:
SELECT Year(OrderDate), CategoryName, SUM(Quantity) as TotalQuantity
FROM ([Order Details]
INNER JOIN Products ON [Order Details].ProductID = Products.ProductID
INNER JOIN Categories ON Products.ProductID = Categories.CategoryID)
GROUP BY Year(OrderDate), CategoryName
ORDER BY TotalQuantity DESC;
此外,如果您只想捕获特定年份的数据,请添加日期过滤器。希望它有所帮助。