Amazon Redshift 中的数据透视和求和

Pivot and Sum in Amazon Redshift

我有以下表格

表 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 中似乎无法对它们进行旋转。

谢谢。

这看起来是一个数据透视查询。我认为这符合您的要求:

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
;