Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transpose columns to rows in BigQuery

For BigQuery, How can I transpose columns 'Ds Hrc Shm', 'Ds Orc Cwp' ... into rows and also transpose rows inside 'sku' into columns and keep the value inside to be the same

FROM

   SKU     | Ds Hrc Shm  | Ds Orc Cwp  | Ds Orc Mwp  
DB-MIX-HTS        1             1              1
DB-ORC-TUS        0             1              1

INTO

          DB-MIX-HTS | DB-ORC-TUS 
Ds Hrc Shm      1           0
Ds Orc Cwp      1           1
Ds Orc Mwp      1           1
  

Should I use pivot / unvipot or any simple way to do?

I try to use pivot but I cannot declare a column header inside IN

SELECT *
FROM
(
SELECT `manual_input.sku_translations`.`ds_hrc_shm` AS `ds_hrc_shm`, 
`manual_input.sku_translations`.`sku` AS `sku_1`,
 FROM `manual_input.sku_translations`
 ) 
 PIVOT
(
 SUM(`ds_hrc_shm`) FOR `sku_1` IN (['DB-ORC-TWS'], ['DB-MIX-SGT'])
 ) 

Here's the sample of data

like image 667
Issada Intakaew Avatar asked Oct 24 '25 04:10

Issada Intakaew


1 Answers

Consider below approach

select * from (
  select * replace(replace(SKU, '-', '_') as SKU)
  from `manual_input.sku_translations`
  unpivot (value for col in (`Ds Hrc Shm`, `Ds Orc Cwp`, `Ds Orc Mwp`))
)
pivot (any_value(value) for SKU in ('DB_MIX_HTS', 'DB_ORC_TUS'))    

if to apply to sample data in your question as

with `manual_input.sku_translations` as (
  select 'DB-MIX-HTS' SKU, 1 as `Ds Hrc Shm`, 1 as `Ds Orc Cwp`, 1 as `Ds Orc Mwp` union all
  select 'DB-ORC-TUS', 0, 1, 1
)           

output is

enter image description here

like image 72
Mikhail Berlyant Avatar answered Oct 26 '25 19:10

Mikhail Berlyant