【问题标题】:Pivot and Sum in Amazon RedshiftAmazon Redshift 中的数据透视和求和
【发布时间】:2022-01-15 03:30:55
【问题描述】:

我有以下表格

表1

id name
1  A
3  B

表2

id label   value
1   tag     a
1   tag     b
1   time    10
1   time    20
1   score   20
2   tag     a
2   time    30
2   score   40 
3   tag     b 
3   time    50
3   time    55
3   score   60

首先我想加入table2如下

select *
from table1 left join on table2 using(id)
where label in ('tag')
id name tag
1   A   a
1   A   b
3   B   b

然后将 table2 与 id 连接起来,然后对它们进行旋转和总结

id name tag time score
1   A   a   10    20
1   A   b   10    20
3   B   b   50    60

我想这很复杂,有什么方法可以实现吗?

在 Redshift 中似乎无法旋转它们。

谢谢。

【问题讨论】:

    标签: sql amazon-web-services amazon-redshift


    【解决方案1】:

    这看起来是一个透视查询。我认为这可以满足您的需求:

    create table table1 (id int, name varchar(16));
    insert into table1 values
    (1, 'A'),
    (3, 'B')
    ;
    
    create table table2 (id int, label varchar(16), value varchar(16));
    insert into table2 values 
    (1,   'tag', 'a'),
    (1,   'tag', 'b'),
    (1,   'time', '10'),
    (1,   'score', '20'),
    (2,   'tag', 'a'),
    (2,   'time', '30'),
    (2,   'score', '40'),
    (3,   'tag', 'b'), 
    (3,   'time', '50'),
    (3,   'score', '60')
    ;
    
    select t2.id, a.name, a.tag_value, sum(decode(label, 'time', value::int)) as total_time, sum(decode(label, 'score', value::int)) as total_score
    from table2 t2
    join (
        select id, name, value as tag_value
        from table1 t1 left join table2 t2 using(id)
        where t2.label in ('tag')
        ) a
    on t2.id = a.id 
    group by 1, 2, 3
    order by 1, 2, 3
    ;
    

    【讨论】:

    • 谢谢你的回答,我可以试试。当我看到我的数据时,table2 timelabel 被重复了。我想将 min(value) 加入表 1,提供的查询有什么变化吗?我改变了我的问题,很抱歉给您带来不便。谢谢
    • 只需将外部选择中的“sum”更改为“min”即可获得 total_time 结果。我确实对您的数据有疑问,因为在 table2 中,您有标签“a”和标签“b”代表 id“1”,看起来这些标签中的每一个都有时间和分值 - 您的数据模型是否需要更新才能知道哪个时间和分数值与哪个标签值对应?
    猜你喜欢
    • 2019-06-05
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    相关资源
    最近更新 更多