繁体   English   中英

SQL带大小写选择-分为多个组

[英]SQL Select with case - select into multiple groups

我有一个国家列表和一个标准化收入列,如下所示:

  country income
  --------------
  es    500
  gb    200
  sg    300
  id    500
  de    450

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

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

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

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

同样的身份(印度尼西亚)将同时属于亚洲和全球

结果表如下所示:

   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

我在想一些CASE语句

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

但是我不确定如何从这里得到全球小组。 这并不一定要通过一个CASE语句来完成-开放的建议。

 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

我可以通过小组分配来做到这一点:

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;

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

暂无
暂无

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

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