Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

I have a table with 3 fields

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

I want to pull the sum of Tax for each state.

Tax   State
.75   TX
.5    AZ
.1    AL

How would I write a query to do this?

like image 396
tomjung Avatar asked Apr 10 '12 17:04

tomjung


1 Answers

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,
  State
FROM table
GROUP 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...

like image 122
Michael Berkowski Avatar answered Oct 18 '22 21:10

Michael Berkowski