【问题标题】:How to convert or transpose rows to columns in SQL without using pivot?如何在不使用数据透视的情况下将行转换或转置为 SQL 中的列?
【发布时间】:2021-06-29 12:47:24
【问题描述】:

我在 SQL 中转置数据时遇到了一个问题。例如下面给出的表格

id source_name value
1 cp x
1 cp y
1 hi a
2 li b
2 cp c
2 li d
3 li e

我需要以下格式的表格(转置但带有字符串聚合)-

id cp hi li mi
1 x,y a null null
2 c null b,d null
3 null null null d

使用当前的 sql 查询,我得到以下格式的表格。

id cp hi li mi
1 x a null null
2 c null b null
3 null null null d

任何人都可以在 SQL(平台 - Bigquery)中调整查询或建议新查询吗?

当前查询 -

select id, any_value(if(source_name = 'cp', value, null)) as cp,
any_value(if(source_name = 'hi', value, null)) as hi,
any_value(if(source_name = 'li', value, null)) as li
any_value(if(source_name = 'mi', value, null)) as mi
from table_name group by id

【问题讨论】:

  • 只是好奇-为什么without using pivot?你有什么用例不想做最好的方式(这是枢轴)? :o)

标签: sql google-bigquery transpose


【解决方案1】:

改用PIVOT operator

select *
from `project.dataset.table`
pivot (string_agg(value) for source_name in ('cp', 'hi', 'li', 'mi'))    

如果应用于您问题中的样本数据

输出是

如果您想让它为您动态构建列列表,请查看https://stackoverflow.com/a/67479622/5221944

【讨论】:

    【解决方案2】:

    尝试STRING_AGG 而不是any_value

    select id, string_agg(if(source_name = 'cp', value, null)) as cp,
    string_agg(if(source_name = 'hi', value, null)) as hi,
    string_agg(if(source_name = 'li', value, null)) as li
    string_agg(if(source_name = 'mi', value, null)) as mi
    from table_name group by id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 2023-01-03
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      相关资源
      最近更新 更多