假设我有一个Sales表,其中包含ProductID,Date,......等一些其他数据。如果我想查找某一年销售的产品数量,我会使用哪种查询?
我有类似的东西:
SELECT YEAR(Date) AS Year, COUNT(ProductID) FROM Sales GROUP BY Year ORDER BY Year;
但这不正确。基本上我想要一个像这样的结果集:
| Year | ProductsSold
| 2000 | 57306
| 2001 | 39683
| 2002 | 30693
| 2003 | 63966
我知道我需要一个GROUP BY,但我想不出如何做到这一点。
答案 0 :(得分:3)
此答案显示使用SQL Server语法转义的关键字,因为您为列名和别名使用了关键字。
您可能打算按应用于YEAR
列的Date
功能(即YEAR([Date])
)而不是Year
别名进行分组:
SELECT YEAR([Date]) AS [Year], COUNT(ProductID) AS ProductsSold
FROM Sales
GROUP BY YEAR([Date])
ORDER BY [Year];
您无法使用Year
别名的原因是评估SELECT
语句的顺序。
答案 1 :(得分:1)
虽然我喜欢Sam和Michael的答案,但
SELECT YEAR([Date]) AS [Year], COUNT(ProductID) AS ProductsSold
FROM Sales
GROUP BY YEAR([Date])
ORDER BY [Year];
我想添加一个小修改,我建议使用
SELECT YEAR([Date]) AS [Year], COUNT(DISTINCT ProductID) AS ProductsSold
为了获得销售的“不同”产品数量。否则,如果一个产品多次出现,您也会多次计数。如果你想做类似的事情,你可能有一个数量列,也许
SELECT YEAR([Date]) AS [Year], SUM(Quantity) AS ProductsSold
或类似的东西会更好。
答案 2 :(得分:0)
SELECT YEAR(Date)AS Year,COUNT(ProductID)FROM Sales GROUP BY YEAR(Date)ORDER BY Year;