How do you group the SUM of rows by year in SQL
15,927
Solution 1
You should GROUP BY
Year, not OrderDate:
SELECT YEAR(OrderDate), SUM(TotalDue)
FROM Sales
GROUP BY YEAR(OrderDate)
Order BY OrderDate
Solution 2
You should group by the year of the order date and no the OrderDate itself.
SELECT YEAR(OrderDate) AS `Year`, SUM(TotalDue)
FROM Sales
GROUP BY YEAR(OrderDate)
Order BY Year
Author by
Eda
Updated on June 26, 2022Comments
-
Eda almost 2 years
SELECT YEAR(OrderDate) 'Year', SUM(TotalDue) FROM Sales GROUP BY OrderDate Order BY OrderDate
How do I add each year together as ONE row? I wrote the query above, but the result still has the TotalDue by Year as individual rows. For example
-
sqluser over 9 yearsCannot use alias in GROUP because of query logical process
-
Eda over 9 yearsDId not work. Error: Each GROUP BY expression must contain at least one column that is not an outer reference.
-
Eda over 9 yearsTHANK YOU Andrei. I created the RIGHT answer based on your input. Only the last line was eliminated, because it produced this Error message:Column "Sales.OrderDate" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
-
Ameya Deshpande over 9 years@Eda just provide alias for the year i.e.
YEAR(OrderDate) 'YEAR'
and in group by usYEAR(OrderDate)
OR You can convert date format likeDATEPART(yyyy,OrderDate) 'YEAR'
and group byDATEPART(yyyy,OrderDate)