'Is there a dynamic way in BigQuery to select/create columns with pattern?
Not sure how to sure how to best phrase it, but essentially I need ~50 columns x 12 weeks in BigQuery and was hoping there was a way to do it more efficiently using some sort of logic or function.
I can generate the script in Python, but the end output itself is long and unwieldy. Is there a cleaner way to do it within BigQuery itself?
Example code:
select id,
sum(case when first_week_flag then visit else 0 end) as sum_visit_first_week,
sum(case when second_week_flag then visit else 0 end) as sum_visit_second_week,
... for 12 weeks,
avg(case when first_week_flag then gap else 0 end) as avg_gap_first_week,
avg(case when second_week_flag then gap else 0 end) as avg_gap_second_week,
... for 12 weeks,
etc. for 50 columns
from table
group by id
Potential for simplification:
select id,
sum(case when {WEEK}_flag then visit else 0 end) as sum_visit_{WEEK},
avg(case when {WEEK}_flag then gap else 0 end) as avg_gap_{WEEk},
etc. for 50 columns
from table
group by id
Can anyone point me in the right direction of what to search for? Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|