【发布时间】: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