简体   繁体   English

SQL/DB2 替代扩展 CASE 语句

[英]SQL/DB2 Alternative to Extensive CASE Statements

I have a project where the data in single/multiple columns needs to be classified by group.我有一个项目,其中单/多列中的数据需要按组分类。 My program uses a CASE statement to create more general categories.我的程序使用 CASE 语句来创建更通用的类别。 Since my code is quickly becoming unwieldy I don't think I have a very good approach.由于我的代码很快变得笨拙,我认为我没有一个很好的方法。

How can I do better?我怎样才能做得更好?

My Db2 query uses a 'CASE STATEMENT to generate the 'classification' column:我的 Db2 查询使用“CASE STATEMENT”生成“分类”列:

SELECT id
,plant
,CASE
     
when plant like 'rose'
     
 then 'flower'

when plant like 'wildflower'
 then 'flower'
when plant like 'spruce'
 then 'tree'
when plant like 'willow'
 then 'tree'
when plant like 'peony'
 then 'flower'
when plant like 'oak'
 then 'tree'
else 'unknown'
     
end as classification
FROM green_table

+----+------------+----------------+
| id | plant      | classification |
+----+------------+----------------+
| 1  | rose       | flower         |
+----+------------+----------------+
| 2  | wildflower | flower         |
+----+------------+----------------+
| 3  | spruce     | tree           |
+----+------------+----------------+
| 4  | willow     | tree           |
+----+------------+----------------+
| 5  | peony      | flower         |
+----+------------+----------------+
| 6  | oak        | tree           |
+----+------------+----------------+

Use a join to a derived table:对派生表使用join

select g.*, coalesce(c.classification, 'unknown') as classification
from green_table g left join
     (select 'rose' as plant, 'flower' as classification from sysibm.sysdummy1 union all
      select 'wildflower' as plant, 'flower' as classification from sysibm.sysdummy1 union all
      . . .
     ) c
     on g.plant = c.plant;

I would actually recommend that you have a table called plants with one row per plant and the classification -- and a numeric primary key that you use to join to the name as well.我实际上建议你有一个名为plants的表,每株植物有一行和分类 - 以及一个用于连接名称的数字主键。

Note: This uses string equality rather than like .注意:这使用字符串相等而不是like Equality seems sufficient and like will have a big impact on the performance of join . Equality 似乎就足够了, like将对join的性能产生很大影响。

You can use in operator for listing the same category您可以使用in operator列出相同的类别

SELECT id,plant,
CASE   
  when plant in ('rose','wildflower','peony') then 'flower'
  when plant in ('spruce','willow','oak') then 'tree'
else 'unknown' end as classification
FROM green_table

You can use DECODE() .您可以使用DECODE() It even includes an "else" case.它甚至包括一个“其他”案例。 For example:例如:

SELECT 
  id,
  plant,
  decode(plant, 'rose', 'flower', 'wildflower', 'flower', 'spruce', 'tree',
                'willow', 'tree', 'peony', 'flower', 'oak', 'tree',
                'unknown') as classification
FROM green_table

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM