Postgres:如何获取多列的聚合

时间:2017-04-19 17:44:05

标签: postgresql

我想用postgres实现过滤导航,但我不确定如何从结果集中返回多个字段中每个值的计数。

示例架构:

id, name, status

对于这个查询,我想看到类似的东西(不必模仿这个结构):

name: [(Bob, 20), (Joe, 15), (Sue, 5)]
status[(active, 15), (inactive, 25)]

1 个答案:

答案 0 :(得分:2)

检查Grouping Sets

with t (name, status) as (values
    ('Bob', 'active'),('Bob', 'active'),
    ('Joe', 'inactive'),('Joe', 'active'),('Joe', 'active')
)
select json_object_agg(case g when 1 then 'name' else 'status' end,a)
from (
    select jsonb_agg(jsonb_build_object(coalesce(name,status), total)) as a, g
    from (
        select name, status, count(*) as total, grouping(name,status) as g
        from t
        group by grouping sets ((name),(status))
    ) s
    group by g
) s
;
                                  json_object_agg                                   
------------------------------------------------------------------------------------
 { "name" : [{"Bob": 2}, {"Joe": 3}], "status" : [{"active": 4}, {"inactive": 1}] }