简体   繁体   中英

How to unpivot multiple colums to rows in Bigquery sql

I'm struggling to unpivot/pivot using SQL.

I tried UNPIVOT function from BIGQUERY documentation but I succeded to unpivot only ONE colums by using the code below but not multiple at the same time

SELECT ... FROM
UNPIVOT(mail_sent FOR metric IN (mail_sent))

Here is the table I've got

month mail_sent mail_received mail_opened
01 2000 1900 500
02 2200 2000 700
03 1900 1800 400

Here is what I want to have, keep the month in colums and have ALL the rest in rows:

values 01 02 03
mail_sent 2000 2200 1900
mail_received 1900 2000 1800
mail_opened 500 700 400

Any idea of how to do it? Thanks a lot !

I found the solution:

SELECT month, metric, value
  FROM final 
  UNPIVOT(value FOR metric IN (mail_sent, mail_received, mail_opened))
  ORDER BY 1

Consider below approach

select * from (
  select * from your_table 
  unpivot(value for metric in (mail_sent, mail_received, mail_opened))
)
pivot (any_value(value) as _ for month in ('01', '02', '03'))       

if applied to sample data in your question - output is

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM