简体   繁体   中英

How to PIVOT table in BigQuery without "IN" argument

So I have a table that looks like this:

list value date
cars 10000 2023-01-28
trucks 20000 2022-12-25
vans 55 2023-01-05
trailers 560 2023-11-11

But I want to pivot it so the list value becomes the column and the values becomes the current value column, like this:

date cars trucks vans trailers
2023-01-28 10000 NA NA NA
2022-12-25 NA 20000 NA NA
2023-01-05 NA NA 55 NA
2023-11-11 NA NA NA 560

What's the best way to do this? I've tried this:

SELECT * FROM 
(select * from `table`)
pivot(sum(list) for list in list)

But this didn't work. Thoughts?

Try going with the CASE expressions:

SELECT date, 
       MAX(CASE WHEN list = 'cars'   THEN value END) AS cars,
       MAX(CASE WHEN list = 'trucks' THEN value END) AS trucks,
       MAX(CASE WHEN list = 'vans'   THEN value END) AS vans
FROM <your_table>
GROUP BY date

Use below simple approach

select * from your_table 
pivot (any_value(value) for list in ('cars', 'trucks', 'vans', 'trailers'))       

if applied to sample data in your question - output is

在此处输入图像描述

you can build that query dynamically (so you will not need to explicitly specify values) and use EXECUTE IMMEDIATE to run it - there are plenty examples of such technique here on SO!

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