google-bigquery - Bigquery:根据不同的 date_trunc 多次运行查询并将结果合并,而不是多个 UNION ALL
问题描述
我希望从核心表中提取和合并类似的聚合,但在时间段截断方面有所不同。例如,这就是我通常会这样做的方式:
with base as (
select
event_datetime
, event_location
, event_uuid
from events_table
)
select
date_trunc(event_datetime, day) as day
, "day" as period_type
, event_location
, count(distinct event_uuid) as number_events
from base
group by day, event_location
union all
select
date_trunc(event_datetime, week) as week
, "week" as period_type
, event_location
, count(distinct event_uuid) as number_events
from base
group by week, event_location
union all
select
date_trunc(event_datetime, week) as month
, "month" as period_type
, event_location
, count(distinct event_uuid) as number_events
from base
group by month, event_location
有谁知道是否有办法避免必须维护三个单独的子查询并拥有一个根据不同的 date_trunc 重新运行的子查询并将结果合并(产生与上面的代码相同的输出)?我知道我以前的公司有人做到了这一点,但我不知道是怎么做到的。
谢谢!
解决方案
考虑以下方法
select
day,
period_type,
event_location,
count(distinct event_uuid) as number_events
from base t,
unnest([
struct('day' as period_type, date_trunc(event_datetime, day) as day),
struct('week', date_trunc(event_datetime, week)),
struct('month', date_trunc(event_datetime, month))
])
group by day, period_type, event_location
推荐阅读
- makefile - make 指令的解释
- laravel - Laravel Eloquent 如何更新数据
- amazon-ec2 - ansible-playbook 等待 ssh 超时并出现 ping 错误,但在本地工作
- ios - 指定最小单元格高度会产生警告吗?
- xamarin.forms - IMarkupExtension - 在编译期间检查属性类型 (xamarin.forms)
- github - 使用 Saltstack 构建包
- cygwin - Cygwin 无法设置 db_home
- java - 在 ServletContext 资源 [/WEB-INF/spring-security.xml] 中定义的名称为“offlineTokenServices”的无效 bean 定义
- google-apps-script - 用户上传的 Google 表单文件不是问题
- jquery - DataTable 问题在重新加载时删除 thead 子项