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...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.