【发布时间】: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