根据 when 语句中的不同日期参数多次运行查询并合并结果,而不是多个 UNION ALL
Posted
技术标签:
【中文标题】根据 when 语句中的不同日期参数多次运行查询并合并结果,而不是多个 UNION ALL【英文标题】:Run a query multiple times based on different date parameters in the when statements and union the results, instead of multiple UNION ALLs 【发布时间】:2021-07-27 02:20:06 【问题描述】:我希望从核心表中提取和合并类似的聚合,但在 WHEN 语句中定义的日期期间有所不同。我通常会这样做:
with base as (
select
event_datetime
, event_location
, event_uuid
from events_table
)
select
"last_30_days" as period
, event_location
, count(distinct event_uuid) as number_events
from base
where event_datetime >= current_date - 30
group by event_location
union all
select
"last_60_days" as period
, event_location
, count(distinct event_uuid) as number_events
from base
where event_datetime >= current_date - 60
group by event_location
union all
select
"all_time" as period
, event_location
, count(distinct event_uuid) as number_events
from base
where event_datetime >= current_date - 10000
group by event_location
有谁知道是否有办法避免必须维护三个独立的子查询并拥有一个根据不同时期重新运行的子查询并将结果合并(产生与上述代码相同的输出)?
【问题讨论】:
【参考方案1】:考虑以下方法
select
period,
event_location,
count(distinct if(event_datetime >= current_date - days, event_uuid, null)) as number_events
from base,
unnest([
struct('last_30_days' as period, 30 as days),
struct('last_60_days', 60),
struct('all_time', 10000)
])
group by period, event_location
【讨论】:
很高兴它对你有用 - 也考虑投票赞成答案以上是关于根据 when 语句中的不同日期参数多次运行查询并合并结果,而不是多个 UNION ALL的主要内容,如果未能解决你的问题,请参考以下文章