一列中的值总和作为单独的列

sum of values in one column as separate columns

我的 table 中有三列。 datead_idaction_typevalue。我希望 action_type 列中的值成为单独的列,并与列 value 中的值的关联 SUM 相结合。数据如下所示:

date      ad_id        action_type        value
7/11       1            post               2
7/11       1            post               1
7/11       1            click              100
7/11       2            post               4
7/11       2            click              20
7/11       2            click              3

期望的输出是:

date      ad_id         post        click
7/11       1            3            100
7/11       2            4            23

我尝试了以下方法,但我的查询中显然缺少 value 列,找不到正确的语法将其包含在总和中。

select 
    date,
    ad_id,
    sum(case when action_type = 'post' then 1 else 0 end) as post_,
    sum(case when action_type = 'click' then 1 else 0 end) as clicks
from `my_table`
group by 1,2

除了使用的求和值外,一切似乎都是正确的。只需在查询中使用列值而不是 1。

select 
    date,
    ad_id,
    sum(case when action_type = 'post' then value else 0 end) as post_,
    sum(case when action_type = 'click' then value else 0 end) as clicks
from `my_table`
group by 1,2

如果您真的是指 BigQuery(基于原始标签)

select *
from `my_table`
pivot (sum(value) for action_type in ('post', 'click'))           

如果应用于您问题中的示例数据 - 输出为