Skip to content
Advertisement

BigQuery SQL reshape four columns into one column with name of column as value

I currently have a table that looks like:

id      code_44145  code_44146  code_44207  code_44208  
6580671    1             0          0           0
1639363    0             1          0           0

Is it possible to reshape my data into:

id          code    
6580671    44145
1639363    44146

Where the name of the column equal to 1 becomes the value of code in the new reshaped dataset. I have already presorted the dataset such that there will be no case where more than one column is equal to 1.

Advertisement

Answer

Consider below approach

select id, trim(col, 'code_') code 
from data
unpivot (code for col in (code_44145, code_44146, code_44207, code_44208))
where code !=0     

if applied to sample data in your question – output is

enter image description here

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement