【问题标题】:SQL: query that creates more than 1 value per IDSQL:为每个 ID 创建超过 1 个值的查询
【发布时间】:2017-05-09 10:36:59
【问题描述】:

我有下表

我是 SQL 新手,我想创建一个新列,根据满足的条件为 ID 分配特定值。想象一下,当条件 1 = 'Y' 时,分配了值 'Value1',而当条件 2 和条件 3 都等于 'Y' 时,分配了值 'Value2'。所以这意味着对于 ID 1,“Value1”和“Value2”的所有条件都得到满足。所以输出应该是这样的:

因此请注意,ID = 1 没有两行,一个用于满足条件的每个值,对于 ID = 3 和 ID = 4,没有任何条件满足,因此它们被分配为 null。关于如何做到这一点的任何想法?

【问题讨论】:

    标签: mysql sql case


    【解决方案1】:

    我看不出case 对此有何用处。这是一个使用union all的方法:

    select id, 'Value1'
    from t
    where condition1 = 'Y'
    union all
    select id, 'Value1'
    from t
    where condition2 = 'Y' and condition3 = 'Y'
    union all
    select id, NULL
    from t
    where not (condition1 = 'Y' or (condition2 = 'Y' and condition3 = 'Y'));
    

    如所写,代码假定条件绝不是NULL,但这很容易合并。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-23
      • 2013-04-05
      • 2015-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多