【问题标题】:SQL - return each column and it's sum as rowsSQL - 返回每一列,它的总和为行
【发布时间】:2018-01-21 13:33:21
【问题描述】:

我有一张这样的桌子:

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

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

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

基本上我需要字段的名称和总和。可以用sql查询吗?

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

【问题讨论】:

  • 您使用的是哪个 dbms?
  • 使用 SQLite 和 Qt

标签: sql sqlite select


【解决方案1】:

您需要取消透视数据并进行聚合

这是一个 ANSI SQL 方法

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

【讨论】:

    【解决方案2】:

    如果您希望每个值位于单独的行中,那么 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 是标准的)。

    【讨论】:

      【解决方案3】:

      你可以这样做:

      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
      

      【讨论】:

        猜你喜欢
        • 2022-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-10
        • 2020-10-22
        • 2018-07-06
        • 1970-01-01
        • 2022-12-03
        相关资源
        最近更新 更多