Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge three boolean columns into one enumerated column

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
like image 670
AaronThomson Avatar asked Dec 01 '25 08:12

AaronThomson


2 Answers

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
like image 82
Kyle Hale Avatar answered Dec 02 '25 23:12

Kyle Hale


chr(65 + TypeB + 2*TypeC) as Type

Another solution:

decode(TypeB-TypeC, 0, 'A', 1, 'B', 'C') as Type
like image 23
Egor Skriptunoff Avatar answered Dec 02 '25 22:12

Egor Skriptunoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!