Reputation: 763
I am migrating data from a DB with a table containing 3 boolean columns which are, in concept, mutually exclusive. eg:
| TypeA | TypeB | TypeC |
| 0 | 1 | 0 |
| 0 | 0 | 1 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 0 | 0 |
I need to merge these three booleans into a single column based on which of the 3 boolean columns is set to true. The result I'm after would look something like:
| Type |
| B |
| C |
| B |
| A |
| A |
So far, I have come up with the following, however it feels a bit messy. Is there a better way?
SELECT
CASE WHEN TypeA= 1
THEN 'A'
ELSE
CASE WHEN TypeB= 1
THEN 'B'
ELSE
CASE WHEN TypeC= 1
THEN 'C'
END
END
END as Type
FROM TABLE
Upvotes: 2
Views: 497
Reputation: 23747
chr(65 + TypeB + 2*TypeC) as Type
Another solution:
decode(TypeB-TypeC, 0, 'A', 1, 'B', 'C') as Type
Upvotes: 2
Reputation: 8120
You can stack your conditionals in a CASE statement like so
CASE
WHEN TypeA = 1 THEN 'A'
WHEN TypeB = 1 THEN 'B'
WHEN TypeC = 1 THEN 'C'
END as Type
Upvotes: 8