如何在 SQL 中获取列式总和?

How to get column wise sum in SQL?

我有一个复杂的查询,我在不同的列中获取各种类别的计数。

这是我的查询的输出:

    district |  colA  |  colB  |  colC
    ------------------------------------
    DistA    |  1     |   1    |   3
    DistB    |  2     |   0    |   2
    DistC    |  2     |   1    |   0
    DistD    |  0     |   3    |   4
    ..

这是我的查询:

select
  q1."district",
  coalesce(max(case q1."type" when 'colA' then q1."type_count" else 0 end), 0) as "colA",
  coalesce(max(case q1."type" when 'colB' then q1."type_count" else 0 end), 0) as "colB",
  coalesce(max(case q1."type" when 'colC' then q1."type_count" else 0 end), 0) as "colC"
from (
  select
    d."name" as "district",
    t."name" as "type",
    count(t.id) as "type_count"
  from
    main_entity as m
  inner join type_entity as t on
    m."type_id" = t.id
  inner join district as d on 
    m."district_id" = d.id
  where
    m."delete_at" is null
  group by
    d."name",
    t.id
) as q1
group by
  q1."district"

我想修改这个查询,以便我可以获得最后一行中每一列的总和,如下所示:

 district |  colA  |  colB  |  colC
    ------------------------------------
    DistA    |  1     |   1    |   3
    DistB    |  2     |   0    |   2
    DistC    |  2     |   1    |   0
    DistD    |  0     |   3    |   4
    ..
    Total    |  5     |   5    |   9

我尝试通过添加以下内容将 group by + rollup 用于上述查询:

...
group by rollup (q1."district")

它在底部添加了一行,但值类似于它前面一行的值,而不是它前面所有行的总和,所以基本上是这样的:

 district |  colA  |  colB  |  colC
    ------------------------------------
    DistA    |  1     |   1    |   3
    ..
    DistD    |  0     |   3    |   4
    Total    |  0     |   3    |   4

那么,我怎样才能从我的查询中得到按列的一些呢?

试试这个:

With temp as 
(    --your query from above
    select
      q1."district",
      coalesce(max(case q1."type" when 'colA' then q1."type_count" else 0 end), 0) as "colA",
      coalesce(max(case q1."type" when 'colB' then q1."type_count" else 0 end), 0) as "colB",
      coalesce(max(case q1."type" when 'colC' then q1."type_count" else 0 end), 0) as "colC"
    from (
      select
        d."name" as "district",
        t."name" as "type",
        count(t.id) as "type_count"
      from
        main_entity as m
      inner join type_entity as t on
        m."type_id" = t.id
      inner join district as d on 
        m."district_id" = d.id
      where
        m."delete_at" is null
      group by
        d."name",
        t.id
    ) as q1
    group by
      q1."district"
)

select t.* from temp t
UNION
select sum(t1.colA),sum(t1.colB),sum(t1.colC) from temp t1