Let's say I have 5 columns, which could all contain the same value. I want to calculate a new column that tells me whether a specific value occurs more than once. Example of desired outputs with different situations:
I want to scan all rows that contains at least one of value '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 |
A 'case when' would in theory be possible, but going through all the options is not doable: this requires too many combinations. Maybe some inner query?
Edit:
I actually found a solution, by making a join. But the answer of Gordon Linoff is much more clean.
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