如何在SQL查询中用统一术语归类列中特定值?
统一吉他类乐器的视图统计方案
我有一张名为playson的表,存储了表演者及其对应的乐器信息,其中包含多种吉他类型,例如lead guitar、rhythm guitar和acoustic guitar。
当前通过以下视图可查询出15种不同乐器:
create or replace view instrument_count as select distinct instrument from playson
执行查询后的结果:
music=# select * from instrument_count; instrument ----------------- violin guitars lead guitar synthesizer percussion mandolin flute rythm guitar bass keyboard drums banjo tambourine saxophone acoustic guitar (15 rows)
需求说明
需要将acoustic guitar、lead guitar、rhythm guitar(含拼写错误的rythm guitar)以及guitars统一归类为guitar,最终统计结果应为12种不同乐器。要求不能修改原始表列,仅通过视图实现,且不能丢失仅演奏细分吉他类型的表演者信息。
原实现方案(繁琐版)
最初采用嵌套replace的方式实现,但代码可读性差、维护不便:
create or replace view instrument_list as select performer, replace(replace(replace(instrument, 'lead guitar', 'guitars'),'rythm guitar' ,'guitars'),'acoustic guitar' ,'guitars' ) as instrument from playson ; -- 统计去重后的乐器数量 create or replace view instrument_count as select distinct instrument from instrument_list
更优雅的解决方案
推荐使用CASE表达式批量匹配目标乐器类型,代码清晰易维护:
-- 创建统一乐器名称的视图 create or replace view instrument_list as select performer, case when instrument in ('guitars', 'lead guitar', 'rythm guitar', 'acoustic guitar') then 'guitar' else instrument end as instrument from playson; -- 统计去重后的乐器数量 create or replace view instrument_count as select distinct instrument from instrument_list;
如果后续可能新增更多吉他细分类型,也可以用模糊匹配简化判断(需确认无其他含"guitar"的非吉他类乐器,避免误归类):
create or replace view instrument_list as select performer, case when instrument like '%guitar%' then 'guitar' else instrument end as instrument from playson;
修改后,instrument_count视图将输出12种不同乐器,同时完整保留所有表演者的乐器关联信息。
内容的提问来源于stack exchange,提问作者Rayyan Khan
相关产品推荐
相关产品推荐

