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?
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With