[英]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 ![]() |
M![]() |
A![]() |
2022-03-25 ![]() |
P ![]() |
A![]() |
2022-02-03 ![]() |
S![]() |
B![]() |
2022-02-20 ![]() |
Q![]() |
B![]() |
2022-03-10 ![]() |
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 ![]() |
Month-1![]() |
---|---|---|
A![]() |
M;P ![]() |
S![]() |
B![]() |
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.