案例条件(WHEN,IN)和COALESCE

时间:2016-03-30 16:09:43

标签: sql postgresql

我正在运行这样的PostgreSQL查询:

SELECT way, way_area,
  CASE COALESCE(landuse, leisure, highway, amenity, tourism)
    WHEN 'industrial' THEN 'industrial'
    WHEN 'park' THEN 'park'
    WHEN 'common' THEN 'park'
    WHEN 'garden' THEN 'park'
    WHEN 'playground' THEN 'park'
    ELSE 'other'
  END AS class
FROM planet_osm_polygon

有没有办法使用IN检查合并后的值是否在一组值中,而不是编写单独的WHEN语句?类似的东西:

WHEN x IN ('park','common','garden','playground')

而不是:

WHEN 'park' THEN 'park'
WHEN 'common' THEN 'park'
WHEN 'garden' THEN 'park'
WHEN 'playground' THEN 'park'

2 个答案:

答案 0 :(得分:1)

在你的问题中,使用可以使用when x in ('a', 'b', 'c')...,但为了避免重复,最好使用这样的内联视图:

select
  way,
  way_area,
  case when x in ('park','common','garden','playground') then 'park'
       when x = 'industrial' then 'industrial'
       else 'other'
  end as class
from (select way, way_area, COALESCE(landuse, leisure, highway, amenity, tourism) x
      from planet_osm_polygon
      where...) as t

在您x别名(coalesce(...))后,您可以在查询中引用它。然后,您可以在casewhen表达式中使用它。您还可以在incase表达式中使用when

答案 1 :(得分:0)

使用case有两种方法:

Case X when Y then Z When A then B else C end ...

case when X = Y and A=B then Z when X=Y and A=C then Y end

第二个选项为您提供了更大的灵活性,并允许使用复合条件。 所以...

CASE WHEN coalesce(landuse,leisure, highway, amenity, tourism) = 'industrial' 
     THEN 'industrial' 
     WHEN coalesce(landuse,leisure, highway, amenity, tourism) in   
                  ('park','common','garden','playground') 
     THEN 'park' 
     ELSE 'other'
END as class