【问题标题】:merge values in select合并选择中的值
【发布时间】:2025-11-23 11:10:01
【问题描述】:
我有下一部分查询:
SELECT types, count
FROM ...
结果是下一个:
types count
soft 3
lite soft 2
middle soft 7
hard soft 2
other 5
我需要的是合并结果 soft、lite soft 和 other as other。
获得下一张桌子:
types count
middle soft 7
hard soft 2
other 9
【问题讨论】:
标签:
sql
postgresql
group-by
count
case
【解决方案1】:
您可以使用case 表达式`:
select (case when type in ('middle soft', 'hard soft') then type else 'other' end) as type,
sum(count)
from t
group by type;
如果您希望结果按特定顺序排列——比如在末尾加上other,那么横向连接会有所帮助:
select v.type, sum(count)
from t cross join lateral
(values (case when type in ('middle soft', 'hard soft') then type else 'other' end)
) v(type)
group by v.type
order by (v.type = 'other') asc, -- put it last
count(*) desc;
【解决方案2】:
考虑使用case 表达式对types 进行转码,然后进行聚合:
select
case when types in ('middle soft', 'hard soft') then types else 'other' end as new_types,
sum(count) cnt
from mytable
group by 1