计算多个聚合值并在 1 列中计算它们的最终总和

Calculating multiple aggregated values and calculating their final sum all in 1 column

所以我有一个专栏,其中我在 table 中执行 string_agg,如下所示

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

该字段的值在 0-12 之间

我想要每个数字的总值以及所有这些存储在最后一行的 1 列中。

我的代码是

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

如果

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)

我会使用两个级别的聚合:

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;