运行 根据 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
我希望从核心 table 中提取和合并类似的聚合,但在 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
有谁知道是否有办法避免必须维护三个单独的子查询,并让一个子查询根据不同的时间段重新运行并联合结果(产生与上面的代码相同的输出)?
考虑以下方法
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
我希望从核心 table 中提取和合并类似的聚合,但在 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
有谁知道是否有办法避免必须维护三个单独的子查询,并让一个子查询根据不同的时间段重新运行并联合结果(产生与上面的代码相同的输出)?
考虑以下方法
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