2

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

2
  • Pivot is for rows to col. And unpivot is for col to rows. Go for unpivot.
    – Mr.Batra
    Nov 3, 2021 at 12:02
  • Does this answer your question? How to unpivot in BigQuery?
    – user15846476
    Nov 3, 2021 at 13:40

1 Answer 1

4

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.