[英]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:但我想要 pivot 它所以列表值成为列并且值成为当前值列,如下所示:
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:尝试使用
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.