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
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

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With