在雪花中的多个列上旋转

问题描述 投票:0回答:1

我在雪花表中有以下表格

ID     | NAME | QTY | LAYER
5026767  AB    25    1
5026767  XY    25    3
5026767  QE    50    2
5027016  TI    100   1
5027038  PP    30    1
5027038  CC    30    3
5027038  DD    40    2

我想要聚合的

NAME
QTY
LAYER
为中心。比如跟随输出

ID      | '1' | '2' | '3' | NAME_1 | NAME_2 | NAME_3
5026767  25    25    50    AB       XY       QE  
5027016  100   Null  Null  TI       Null     Null
5027038  30    30    40    PP       CC       DD

我尝试过使用

pivot
,但只有与
number
相关的可用聚合,不适用于
char
。我有什么遗漏的吗?

snowflake-cloud-data-platform pivot aggregate varchar
1个回答
0
投票

如果您只想要一个名称,那么最小/最大是可行的方法..

with cte_data(id,name,qty,layer) as (
    select * from values
    ('5026767','AB', 25 ,   1),
    ('5026767','XY', 25 ,   3),
    ('5026767','QE', 50 ,   2),
    ('5027016','TI', 100,   1),
    ('5027038','PP', 30 ,   1),
    ('5027038','CC', 30 ,   3),
    ('5027038','DD', 40 ,   2)
)
select id
    ,sum(iff(layer=1,qty,null)) as "1"
    ,sum(iff(layer=2,qty,null)) as "2"
    ,sum(iff(layer=3,qty,null)) as "3"
    ,max(iff(layer=1,name,null)) as name_1
    ,max(iff(layer=2,name,null)) as name_2
    ,max(iff(layer=3,name,null)) as name_3
from cte_data

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.