繁体   English   中英

将同一组中的每个列值移动到新列 SQL Big Query

[英]Move each column value from the same group to new column SQL Big Query

尝试将行转置为列时遇到问题。

我的桌子看起来像这样:

在此处输入图像描述

结果表应该是这样的: 在此处输入图像描述

我试图用 PIVOT() 解决这个问题,但后来我意识到情况并非如此。 任何人都可以帮我吗?

编辑 1:名字的数量不是无限的(最多 4 个)。

编辑 2:当名称列中有 NULL 时,我意识到我丢失了所有行。

我知道我可以用 UNION 来做,但是这个问题有更优雅的解决方案吗?

在此处输入图像描述

期望的结果将是: 在此处输入图像描述

考虑以下选项

select * from (
  select *
  from your_table, 
  unnest(split(name, ', ')) word with offset
)
pivot (min(word) as name for offset + 1 in (1, 2, 3))   

如果应用于您问题中的示例数据

with your_table as (
  select 'x1' id, 'yellow' name union all
  select 'x2', 'orange' union all
  select 'x3', 'pink, blue' union all
  select 'x4', 'pink, blue, yellow' 
)    

output 是

在此处输入图像描述

这取决于您要拆分成新列的名称数量。 使用您共享的数据,您可以尝试以下查询:

SELECT DISTINCT t1.id, t1.name,
split(t1.name, ', ')[SAFE_offset(0)] as name_1,
split(t1.name, ', ')[SAFE_offset(1)] as name_2,
split(t1.name, ', ')[SAFE_offset(2)] as name_3
from `dataset.table` as t1

这带来了以下 output:

在此处输入图像描述

我使用SAFE_OFFSET是因为如果你只使用OFFSET id 1,2,3 将不允许它,因为它们会带来空值。

当名称列中有 NULL 时,如何保留行? 感谢您的帮助!

考虑以下

select * from (
  select *
  from your_table
  left join unnest(split(name, ', ')) word with offset
)
pivot (min(word) as name for offset + 1 in (1, 2, 3))        

如果应用于您问题中的示例数据

with your_table as (
  select 'x1' id, 'yellow' name union all
  select 'x2', 'orange' union all
  select 'x3', 'pink, blue' union all
  select 'x4', 'pink, blue, yellow' union all 
  select 'x5', null union all
  select 'x6', null 
)              

output 是

在此处输入图像描述

暂无
暂无

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

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