在1列中计算多个汇总值并计算其最终总和

时间:2018-07-12 08:00:08

标签: sql postgresql postgresql-9.3

因此,我有一列在表中按如下方式进行string_agg

select buildingid, string_agg(distinct cast(obligatioNr as varchar(2)), ', ') as SPJ
...

此字段的值介于0到12之间

enter image description here

我希望每个数字的总和全部存储在1列的最后一行中。

enter image description here

我的代码与

相似
with results as 
(
    select  id, amount, SPJ
    FROM 
    (
        SELECT building.id as ids,
            count(distinct s.studentnr) as amount,
            string_agg(distinct cast(so.obligationnr as varchar(2)), ', ') as SPJ,

        from ....

        GROUP BY building.id
    ) t

    GROUP BY ids, amount,SPJ

    ORDER BY ids
)
    SELECT *
    FROM results 
    UNION all
    SELECT NULL as ids,
    SUM(amount),
    null as SPJ
    FROM results 

我正在使用Postgres 9.3

2 个答案:

答案 0 :(得分:1)

如果

db-# select v from t;
    v
---------
 8,9
 9,10,11
(2 rows)

然后:

db=# with t(v) as (values('8,9'),('9,10,11'))
,m  as (select unnest(string_to_array(v,',')) u from t)
select u||':'||count(u) from m group by u order by u::int;
 ?column?
----------
 8:1
 9:2
 10:1
 11:1
(4 rows)

最后:

db=# with t(v) as (values('8,9'),('9,10,11'))
,m  as (select unnest(string_to_array(v,',')) u from t)
,f as (select u||':'||count(u) a from m group by u order by u::int)
select string_agg(a,',') from f;
    string_agg
-------------------
 8:1,9:2,10:1,11:1
(1 row)

啊,一起:

db=# with t(v) as (values('8,9'),('9,10,11'))
,m  as (select unnest(string_to_array(v,',')) u from t)
,f as (select u||':'||count(u) a from m group by u order by u::int)
select v from t union all select string_agg(a,',') from f;
         v
-------------------
 8,9
 9,10,11
 8:1,9:2,10:1,11:1
(3 rows)

答案 1 :(得分:0)

我将使用两种聚合级别:

select string_agg(o2 || ':' || cnt, ', ') as all_values
from (select cast(obligatioNr as varchar(2)) as o2,
             count(distinct buildingid) as cnt
      from . . .
      group by o2
     ) x;