Skip to content
Advertisement

SQL:pivot: convert each row into many rows depends on a condition

I have been trying to solve this but could not figure it out.

so this is the table and more columns could be added:

+------------+-----------+------------+-----------+------------+------------+
| patient_ID | code_ID   | happy?     | mad?      |  smiling?  |    scared? |
+------------+-----------+------------+-----------+------------+------------+
|     kkk    |  kgg      | 1          |    0      |    1       |      1     |
+------------+-----------+------------+-----------+------------+------------+
|     2k2    |  2g2      | 0          |    1      |    0       |      1     |
+------------+-----------+------------+-----------+------------+------------+

So if the value is one then I will display it in a different row but with the value being the column header itself My boss suggested using pivot to solve this but I am open to any way.

output should be like this:

+------------+-----------+------------+
| patient_ID | code_ID   | segment    | 
+------------+-----------+------------+
|     kkk    |  kgg      | happy?     |
+------------+-----------+------------+
|     kkk    |  kgg      | smiling?   | 
+------------+-----------+------------+
|     kkk    |  kgg      | scared?    |
+------------+-----------+------------+
|     2k2    |  2g2      | mad?       | 
+------------+-----------+------------+
|     2k2    |  2g2      | scared?    |
+------------+-----------+------------+

Advertisement

Answer

One method is union all:

select patient_id, code_id, 'happy?' as segment
from t
where `happy?` = 1
union all
select patient_id, code_id, 'mad?'
from t
where `mad?` = 1
union all
select patient_id, code_id, 'smiling?'
from t
where `smiling?` = 1
union all
select patient_id, code_id, 'scared?'
from t
where `scared?` = 1;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement