简体   繁体   English

每月 Select 行产品事件并将其连接到另一个表中

[英]Select events of a product in rows for each month and put concatenate in another table

I have a Biguery table like this:我有一个像这样的 Biguery 表:

Product产品 Date日期 Event事件
A一种 2022-03-08 2022-03-08 M
A一种 2022-03-25 2022-03-25 P P
A一种 2022-02-03 2022-02-03 S小号
B 2022-02-20 2022-02-20 Q
B 2022-03-10 2022-03-10 R R

Based on current date (2022-03-29), I need to insert in another Bigquery table in this format:根据当前日期 (2022-03-29),我需要以这种格式插入另一个 Bigquery 表:

Product产品 Month-0 0月 Month-1第 1 个月
A一种 M;P M;P S小号
B R R Q

I appreciate if you can help me.如果你能帮助我,我将不胜感激。

Regards.问候。

using pivot and string_agg will do this aggregation使用 pivot 和 string_agg 将执行此聚合

With tbl as
(SELECT "A" Product , date "2022-03-08" date, "M" event
Union ALL SELECT "A", "2022-03-25", "P"
Union ALL SELECT "A", "2022-02-03", "S"
Union ALL SELECT "B", "2022-02-20", "Q"
Union ALL SELECT "B", "2022-03-10", "R"
)

SELECT *, 
from 
(SELECT Product,event, date_diff(current_date(),date,month) as diff
from tbl)
PIVOT(string_agg(event,";") month FOR diff IN (0,1,2)  )

Consider below approach考虑以下方法

execute immediate (select '''
select * from your_table
pivot(string_agg(event,";") month for date_diff(current_date(),date,month) in (''' || string_agg('' || value) || '''))
'''
from (
  select max(date_diff(current_date(),date,month)) max_diff from your_table
), unnest(generate_array(0, max_diff)) value
)       

if applied to sample data in your question - output is如果应用于您问题中的示例数据 - output 是

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM