【问题标题】:SQL Select with case - select into multiple groupsSQL Select with case - 选择多个组
【发布时间】:2016-08-19 04:26:07
【问题描述】:

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

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

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

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

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

所以这会使 es(西班牙)同时属于欧盟和全球

类似地,id(印度尼西亚)将同时属于亚洲和全球

结果表会是这样的:

   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'

但我不确定如何从这里获取 Global 组。这必须通过 CASE 语句完成 - 接受建议。

【问题讨论】:

  • 您使用的是什么平台? oracle、db2、sql server、mysql,还有什么?
  • 我目前正在使用 MySQL,但我正在寻找与产品无关的解决方案,因为它可以随时移植到 Oracle 或 Vertica。
  • mysql 基本上与其他一切都不兼容。

标签: sql case


【解决方案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

【讨论】:

    【解决方案2】:

    我会通过小组作业来做到这一点:

    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;
    

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

    【讨论】:

    • 我接到一个电话,所以我错过了回答,但我会使用 VALUES 而不是 UNION ALL 有理由不使用 VALUES 吗?
    • @Hogan。 . .因为问题没有用 SQL Server 或 Postgres 标记
    • 到 DB2 或 Oracle。 VALUES 是多年前的 sql 标准。
    猜你喜欢
    • 2021-06-14
    • 2021-02-05
    • 2011-03-09
    • 2015-07-27
    • 2015-11-27
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 2015-10-22
    相关资源
    最近更新 更多