Get the SUM of one column when grouped by another column in SQL Get the SUM of one column when grouped by another column in SQL sql sql

Get the SUM of one column when grouped by another column in SQL


This is a really rudimentary SUM() aggregate. I recommend reading your RDBMS' documentation on aggregate functions and GROUP BY because this is quite elementary.

SELECT  SUM(Tax) AS sumtax,  StateFROM tableGROUP BY State/* Looks like you want descending order */ORDER BY SUM(Tax) DESC

Note that some RDBMS (MySQL, for instance) will allow you to use a column alias in the ORDER BY as in:

ORDER BY sumtax DESC

... where others (Like SQL Server if I recall correctly) will not and you must use the aggregate value there too.

Edit: I just checked and actually SQL Server does seem to allow aliases in the ORDER BY. Pretty sure you can't use an alias in the GROUP BY though...