Samsquanch
Samsquanch

Reputation: 9146

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.

Upvotes: 1

Views: 123

Answers (4)

Charles Bretana
Charles Bretana

Reputation: 146557

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

Upvotes: 2

Taryn
Taryn

Reputation: 247840

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

Upvotes: 3

Scott Stafford
Scott Stafford

Reputation: 44808

select col1, sum(col2) as sum from table group by col1

Upvotes: 3

Kermit
Kermit

Reputation: 34063

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

SELECT col1, SUM(col2)
FROM unicorns
GROUP BY col1

Upvotes: 3

Related Questions