SQL选择大小写 - 选择多个组

时间:2016-08-18 19:56:58

标签: sql case

我有一份国家清单和一系列标准化收入如下:

   region    country income
   -------------------------
   EU        es    500
   EU        gb    200
   ASIA      sg    300
   ASIA      id    500
   EU        de    450
   Global    es    500
   Global    gb    200
   Global    sg    300
   Global    id    500
   Global    de    450

我在这里要完成的是将这些国家分成不同的地理区域和全球区域。

欧盟地区将包含es(西班牙),gb(英国)和de(德国)。 亚洲地区将包含sg(新加坡)和id(印度尼西亚)

现在我还想将每个国家/地区添加到全球地理区域,因此全球区域将包含所有上面列出的国家/地区

因此,这将使es(西班牙)属于欧盟和全球

同样,id(印度尼西亚)将属于亚洲和全球

结果表格如下:

SELECT
    CASE WHEN country IN ('es', 'gb', 'de') 
            THEN 'EU'
         WHEN country IN ('id', 'sg') 
            THEN 'ASIA'

我正在考虑CASE声明中的某些内容

resources

但我不确定如何从这里获得全球小组。这不是通过CASE语句完成 - 对建议开放。

2 个答案:

答案 0 :(得分:1)

 SELECT
    CASE when country in ('es', 'gb', 'de') THEN 'EU'
         when country in ('id', 'sg') THEN 'ASIA'
         END as Region, country,income FROM country

         UNION
 SELECT 'Global',country,income 
          FROM country

答案 1 :(得分:1)

我会在小组作业中这样做:

select reg.region, reg.country, income
from country c join
     (select 'es' as country, 'EU' as region union all
      select 'gb' as country, 'EU' as region union all
      select 'de' as country, 'EU' as region union all
      select 'id' as country, 'EU' as region union all
      select 'sg' as country, 'EU' as region union all
      select 'es' as country, 'GLOBAL' as region union all
      select 'gb' as country, 'GLOBAL' as region union all
      select 'de' as country, 'GLOBAL' as region union all
      select 'id' as country, 'GLOBAL' as region union all
      select 'sg' as country, 'GLOBAL' as region
     ) as reg
     on c.country = reg.country;

我倾向于将国家/地区的地图放在一个单独的表格中。