一种方法是取消透视数据,然后重新聚合:
select w,
sum(case when i = 0 then 1 else 0 end) as w1,
sum(case when i = 1 then 1 else 0 end) as w2,
sum(case when i = 2 then 1 else 0 end) as w3,
sum(case when i = 3 then 1 else 0 end) as w4
from (select array[w1, w2, w3, w4] ws
from t
) t cross join
unnest(ws) w with offset i
group by w;
这是一个更完整的例子:
with t as (
select 1 as slno, '<5' as w1, '<5' as w2, '<5' as w3, '<5' as w4 union all
select 1 as slno, '<5' as w1, '5 to 10' as w2, '<5' as w3, '5 to 10' as w4
)
select w,
sum(case when i = 0 then 1 else 0 end) as w1,
sum(case when i = 1 then 1 else 0 end) as w2,
sum(case when i = 2 then 1 else 0 end) as w3,
sum(case when i = 3 then 1 else 0 end) as w4
from (select array[w1, w2, w3, w4] as ws
from t
) t cross join
unnest(ws) w with offset i
group by w;