简体   繁体   English

我如何在 google BigQuery 上输入 pivot?

[英]how do I pivot this on google BigQuery?

This is the data that I am currently working with.这是我目前正在使用的数据。

x X y a A
3 3个 2 2个 LL
5 5个 2 2个 LL
5 5个 4 4个 LL
3 3个 4 4个 LL
6 6个 7 7 RR RR
8 8个 7 7 RR RR
8 8个 9 9 RR RR
6 6个 9 9 RR RR

I am trying to pivot the table such that it becomes:我正在尝试 pivot 表格,使其变为:

x1 x1 x2 x2 y1 y1 y2 y2 a A
3 3个 5 5个 2 2个 4 4个 LL
6 6个 8 8个 7 7 9 9 RR RR

I've tried AGG and the PIVOT functions, but can't seem to get this to work, and this has to be done using onky Google BQ.我试过 AGG 和 PIVOT 函数,但似乎无法让它工作,这必须使用 onky Google BQ 来完成。 The complete dataset is much larger, so I need a general solution.完整的数据集要大得多,所以我需要一个通用的解决方案。 Any help or suggestions would be appreciated.任何帮助或建议将不胜感激。 Thanks!谢谢!

Below should be good start for you以下应该是您的良好开端

select * from (
  select * from 
  (select *, row_number() over(partition by a) pos from (select distinct x, a from your_table)) 
  full outer join 
  (select *, row_number() over(partition by a) pos from (select distinct y, a from your_table)) 
  using (a, pos)
)
pivot (any_value(x) as x, any_value(y) as y for pos in (1,2))   

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 count of unique 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