SQL - 返回每列,它的总和为行

时间:2018-01-21 13:33:22

标签: sql sqlite select invert

我有一张这样的表:

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

我需要一个选择,它会返回如下内容:

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

基本上我需要字段的名称和它的总和。是否可以使用SQL查询?

PS:如果无法获得字段的名称并且它是动态的总和,我可以逐个输入它们(它们大约是20)。

3 个答案:

答案 0 :(得分:1)

如果您希望每个值位于单独的行中,则会想到union all

select 'field1', sum(field1) from t union all
select 'field2', sum(field2) from t union all
. . .

但是,我建议将值放在一行中:

select sum(field1) as sum_field1, sum(field2) as sum_field2, . . .
from t;

性能要好得多,因为表只需要读一次。

如果您愿意,可以从元数据表构建此类查询。例如,您可以运行:

select replace('select ''[c]'' as field, sum([c]) as [c] from t union all ', '[c]', column_name)
from information_schema.columns
where table_name = <whatever> and column_name like 'field%';

然后复制代码并将其调整为有效的SQL语句(通过删除最终的union all)。

(在某些数据库中,元数据表/视图具有不同的名称,但information_schema.column是标准的。)

答案 1 :(得分:1)

您需要取消数据并进行汇总

这是ANSI SQL方法

select 'field1',sum(field1)
from yourtable 
union all
select 'field2',sum(field2)
from yourtable 
..
select 'fieldn',sum(fieldn)
from yourtable 

答案 2 :(得分:0)

你可以这样做:

select
    (select sum(field1) from tbl) as sum_field1,
    (select sum(field2) from tbl) as sum_field2,
    (select sum(field3) from tbl) as sum_field3,
    (select sum(field4) from tbl) as sum_field4,
    ...
    (select sum(fieldN) from tbl) as sum_fieldN