Initial table :
customer_id | order_A | order_B | order_C | order_D
1 | 1 | 0 | 0 | 1 |
2 | 0 | 1 | 0 | 1 |
3 | 1 | 1 | 0 | 1 |
4 | 0 | 0 | 0 | 1 |
Required Output :
customer_id | order_type |
1 | A |
1 | D |
2 | B |
2 | D |
3 | A |
3 | B |
3 | D |
4 | D |
Initially, my question was marked as duplicate and I was asked to refer the following question : MySQL pivot table
I referred it and also took help of http://archive.oreilly.com/oreillyschool/courses/dba1/ to come up with the following code:
select customer_id,
case when order_A=1 then 'A' end as order_type
from tb1 having order_type is not null
Union all
select customer_id,
case when order_B=1 then 'B' end as order_type
from tb1 having order_type is not null
Union all
select customer_id,
case when order_C=1 then 'C' end as order_type
from tb1 having order_type is not null
Union all
select customer_id,
case when order_D=1 then 'D' end as order_type
from tb1 having order_type is not null order by customer_id,order_type;
This code is indeed giving me the required output, but I was wondering if there was a better way/approach to this question.
Also, it would be great help if someone can help suggest website/books where I can practise such question for interviews.