Let’s say I have a Sales table, that contains columns ProductID, Date, … some other data. If I want to find how many products were sold in a given year, what query would I use?
I had something like:
SELECT YEAR(Date) AS Year, COUNT(ProductID) FROM Sales GROUP BY Year ORDER BY Year;
but that isn’t correct. Essentially I want a resultset like this:
| Year | ProductsSold
| 2000 | 57306
| 2001 | 39683
| 2002 | 30693
| 2003 | 63966
I know I need a GROUP BY but I just can’t think of how to get this right.
This answer shows keywords escaped using SQL Server syntax, since you used a keyword for your column name and alias.
You probably meant to group by the
YEARfunction applied to theDatecolumn (i.e.,YEAR([Date])) rather than itsYearalias:The reason why you can’t use the
Yearalias is the order in which aSELECTstatement is evaluated.