Get SUM of one column when grouping by another column in SQL

I have a table with three fields

ID  Tax   State
0   .50   TX
1   .25   TX
2   .25   AZ
3   .25   AZ
4   .1    AL

I want to get the tax amount for each state.

Tax   State
.75   TX
.5    AZ
.1    AL

How can I write a query for this?

+5
source share
1 answer

This is truly a rudimentary aggregate SUM(). I recommend reading the RDBMS documentation for aggregate functions and GROUP BYbecause it is pretty basic.

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

Note that some RDBMS (e.g. MySQL) will allow you to use the column alias in ORDER BY, as in:

ORDER BY sumtax DESC

... where others (e.g. SQL Server, if I remember correctly) will not, and you should also use its total value.

: , SQL Server, , ORDER BY. , GROUP BY, ...

+16

All Articles