将同一组中的每个列值移动到新列 SQL Big Query
Move each column value from the same group to new column SQL Big Query
我在尝试将行转置为列时遇到问题。
我的 table 看起来像这样:
结果 table 应该是这样的:
我试图用 PIVOT() 解决这个问题,但后来我意识到情况并非如此。
有人可以帮我吗?
编辑 1:名称的数量不是无限的(最多 4 个)。
编辑 2:我意识到当名称列中有 NULL 时我丢失了所有行。
我知道我可以用 UNION 来解决这个问题,但是这个问题有更优雅的解决方案吗?
期望的结果将是:
这取决于您要拆分成新列的名称数量。使用您共享的数据,您可以尝试以下查询:
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
这会带来以下输出:
我使用 SAFE_OFFSET
因为如果你只使用 OFFSET
id 1,2,3 将不允许它,因为它们会带来空值。
考虑以下选项
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'
)
输出是
How can I keep the rows when there is NULL in name column? I appreciate you help!
考虑以下
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
)
输出是
我在尝试将行转置为列时遇到问题。
我的 table 看起来像这样:
结果 table 应该是这样的:
我试图用 PIVOT() 解决这个问题,但后来我意识到情况并非如此。 有人可以帮我吗?
编辑 1:名称的数量不是无限的(最多 4 个)。
编辑 2:我意识到当名称列中有 NULL 时我丢失了所有行。
我知道我可以用 UNION 来解决这个问题,但是这个问题有更优雅的解决方案吗?
期望的结果将是:
这取决于您要拆分成新列的名称数量。使用您共享的数据,您可以尝试以下查询:
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
这会带来以下输出:
我使用 SAFE_OFFSET
因为如果你只使用 OFFSET
id 1,2,3 将不允许它,因为它们会带来空值。
考虑以下选项
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'
)
输出是
How can I keep the rows when there is NULL in name column? I appreciate you help!
考虑以下
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
)
输出是