【问题标题】:SQL (Redshift): Find if a specific value occurs more than once in multiple columnsSQL(Redshift):查找特定值是否在多个列中出现多次
【发布时间】:2021-08-18 12:55:05
【问题描述】:

假设我有 5 列,它们都可以包含相同的值。我想计算一个新列,该列告诉我某个特定值是否多次出现。不同情况下所需输出的示例:

我想扫描所有包含至少一个值“X”的行:

id A B C D E Result
1 X Y X Z True
2 X Y Y Z False
3 Y Y Z False
4 X X Y X True

“何时”在理论上是可能的,但通过所有选项是不可行的:这需要太多的组合。也许是一些内部查询?

编辑:

实际上,我通过加入找到了解决方案。但 Gordon Linoff 的回答要干净得多。

select id,
case when b.num_X > 1 then True else False end as result 
from foo f
join (
    select a+b+c+d+e as num_X from (
        select 
        id,
        case when A = 'X' then 1 else 0
        end as a,
        case when B = 'X' then 1 else 0
        end as b,
        case when C = 'X' then 1 else 0
        end as c,
        case when D = 'X' then 1 else 0
        end as d,
        case when E = 'X' then 1 else 0
        end as e
        from foo
    )
) b on f.id = b.id

【问题讨论】:

    标签: sql amazon-redshift


    【解决方案1】:

    一种方法是只计算它们:

    select t.*,
           ( (a = 'X')::int + (b = 'X')::int + (c = 'X')::int + (d = 'X')::int + (e = 'X')::int) ) >= 2 as result
    from t;
    

    如果列可以包含NULL 值,那么您需要注意这一点。一种方法是在上面的表达式中使用coalesce()

           ( (coalesce(a, '') = 'X')::int +
             (coalesce(b, '') = 'X')::int +
             (coalesce(c, '') = 'X')::int +
             (coalesce(d, '') = 'X')::int +
             (coalesce(e, '') = 'X')::int)
           ) >= 2 as result
    

    【讨论】:

    • 我知道这很简单,现在我觉得很傻。还是有点新,我不知道你可以这样算..谢谢!
    猜你喜欢
    • 2020-10-26
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    相关资源
    最近更新 更多