简体   繁体   中英

Sum all like columns with the column name as one column, and the total in the other

I have a table with some data similar to this:

col1 | col2
-----------
val1    1
val1    5
val1    7
val2    3
val2    1
val2    4
val3    8

What I would like is a query to produce something like this:

col1 | sum
----------
val1   13
val2   8
val3   8

I've tried doing this with complicated subqueries, but nothing is quite panning out. I think I may be overthinking it.

This should be all you need. This uses the aggregate SUM with a GROUP BY .

SELECT col1, SUM(col2)
FROM unicorns
GROUP BY col1
select col1, sum(col2) as sum from table group by col1

You just need to use the aggregate function sum() with a group by :

select col1, SUM(col2) total
from yourtable
group by col1

See SQL Fiddle with Demo

  Select col1, Sum(col2) sum
  From table
  Group By col1

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM