[英]Select events of a product in rows for each month and put concatenate in another table
我有一個像這樣的 Biguery 表:
產品 | 日期 | 事件 |
---|---|---|
一種 | 2022-03-08 | 米 |
一種 | 2022-03-25 | P |
一種 | 2022-02-03 | 小號 |
乙 | 2022-02-20 | 問 |
乙 | 2022-03-10 | R |
根據當前日期 (2022-03-29),我需要以這種格式插入另一個 Bigquery 表:
產品 | 0月 | 第 1 個月 |
---|---|---|
一種 | M;P | 小號 |
乙 | R | 問 |
如果你能幫助我,我將不勝感激。
問候。
使用 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) )
考慮以下方法
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
)
如果應用於您問題中的示例數據 - output 是
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.