简体   繁体   English

如何在没有“IN”参数的情况下在 BigQuery 中生成 PIVOT 表

[英]How to PIVOT table in BigQuery without "IN" argument

So I have a table that looks like this:所以我有一个看起来像这样的表:

list列表 value价值 date日期
cars汽车 10000 10000 2023-01-28 2023-01-28
trucks卡车 20000 20000 2022-12-25 2022-12-25
vans货车 55 55 2023-01-05 2023-01-05
trailers拖车 560 560 2023-11-11 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:但我想要 pivot 它所以列表值成为列并且值成为当前值列,如下所示:

date日期 cars汽车 trucks卡车 vans货车 trailers拖车
2023-01-28 2023-01-28 10000 10000 NA北美 NA北美 NA北美
2022-12-25 2022-12-25 NA北美 20000 20000 NA北美 NA北美
2023-01-05 2023-01-05 NA北美 NA北美 55 55 NA北美
2023-11-11 2023-11-11 NA北美 NA北美 NA北美 560 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:尝试使用CASE表达式:

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如果应用于您问题中的样本数据 - output 是

在此处输入图像描述

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!您可以动态构建该查询(因此您不需要显式指定值)并使用EXECUTE IMMEDIATE来运行它 - SO 上有很多此类技术的示例!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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