[英]Move each column value from the same group to new column SQL Big Query
I have faced an issue when trying to transpose rows to columns.尝试将行转置为列时遇到问题。
My table looks like this:我的桌子看起来像这样:
And the result table should look like this:结果表应该是这样的:
I tried to solve this problem with PIVOT() but then I realized this is not the case.我试图用 PIVOT() 解决这个问题,但后来我意识到情况并非如此。 Can anyone help me with that?任何人都可以帮我吗?
Edit 1: the number of names is not infinite (4 at most).编辑 1:名字的数量不是无限的(最多 4 个)。
Edit 2: I've realized I've lost all the rows when there is NULL in name column.编辑 2:当名称列中有 NULL 时,我意识到我丢失了所有行。
I know I could do it with UNION, but is there more elegant solution to this problem?我知道我可以用 UNION 来做,但是这个问题有更优雅的解决方案吗?
Consider below option考虑以下选项
select * from (
select *
from your_table,
unnest(split(name, ', ')) word with offset
)
pivot (min(word) as name for offset + 1 in (1, 2, 3))
if applied to sample data in your question如果应用于您问题中的示例数据
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 is output 是
It depends on how many names you want to split into new columns.这取决于您要拆分成新列的名称数量。 With the data that you, shared you can try this query below:使用您共享的数据,您可以尝试以下查询:
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
This brings the below output:这带来了以下 output:
I use SAFE_OFFSET
because if you only use OFFSET
the id 1,2,3 wouldn't allow it because they bring nulls.我使用SAFE_OFFSET
是因为如果你只使用OFFSET
id 1,2,3 将不允许它,因为它们会带来空值。
How can I keep the rows when there is NULL in name column?当名称列中有 NULL 时,如何保留行? I appreciate you help!感谢您的帮助!
Consider below考虑以下
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))
if applied to sample data in your question如果应用于您问题中的示例数据
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
)
the output is output 是
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.