Skip to content
Advertisement

SQL – return each column and it’s sum as rows

I have a table like this:

date | employee_id | field1 | field2 | field3 | ... | fieldN

I need a select which will return something like:

field1 | SUM(field1)
field2 | SUM(field2)
field3 | SUM(field3)
...
fieldN | SUM(fieldN)

Basically I need the field’s name and it’s sum. Is it possible with a sql query?

PS: If it’s not possible to get the field’s name and it’s sum dynamically, I can type them 1 by 1 (they’re about 20).

Advertisement

Answer

you need to unpivot the data and do the aggregation

Here is an ANSI SQL method

select 'field1',sum(field1)
from yourtable 
union all
select 'field2',sum(field2)
from yourtable 
..
select 'fieldn',sum(fieldn)
from yourtable 
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement