sql - 在 SQL/BigQuery 中组合范围
问题描述
我想在 BigQuery 中合并相邻的日期范围。
我有一张这样的桌子:
ID START END
1 2019-01-18 17:34:58 UTC 2019-02-18 12:14:59 UTC
1 2019-02-18 06:04:39 UTC 2019-02-18 08:05:05 UTC
1 2019-02-18 08:05:05 UTC 2019-02-18 10:06:05 UTC
1 2019-02-18 10:06:05 UTC 2019-02-19 11:16:15 UTC
2 2019-01-19 06:02:29 UTC 2019-01-29 11:02:23 UTC
由于中间的三行代表一个分成三部分的范围,我想将它们组合起来,所以表格如下所示:
ID START END
1 2019-01-18 17:34:58 UTC 2019-02-18 12:14:59 UTC
1 2019-02-18 06:04:39 UTC 2019-02-19 11:16:15 UTC
2 2019-01-19 06:02:29 UTC 2019-01-29 11:02:23 UTC
实现这一目标的最佳方法是什么?
解决方案
您需要确定范围的开始位置。在您的情况下,它们似乎具有完全匹配的结束和开始,因此您可以使用lag()
来确定组的开始位置。开始的累积计数提供了一个分组 id,可用于聚合:
select id, min(start) as start, max(end) as end
from (select t.*, countif(prev_end is null or prev_end <> start) over (partition by id order by start) as grp
from (select t.*, lag(end) over (partition by id order by start) as prev_end
from t
) t
) t
group by id, grp;
如果组可以重叠,那么累积最大值通常可以解决问题:
select id, min(start) as start, max(end) as end
from (select t.*, countif(prev_end is null or prev_end <> start) over (partition by id order by start) as grp
from (select t.*,
max(end) over (partition by id order by start rows between unbounded preceding and 1 preceding) as prev_end
from t
) t
) t
group by id, grp;
推荐阅读
- typescript - 如何在 Angular 8 中为延迟加载模块使用通用指令
- java - Spring jpa 无法删除实体,因为表有 fk
- python - 如何在不更改条目的其他变量的情况下更改 tkinter 条目的状态?
- android - 建立连接后如何获取所有firebase推送通知
- android - 如何防止 kivy 应用程序在执行某些后端功能时变得无响应
- python - 我如何将数据从 python django 输出到 html
- c# - 在文本框中显示 SQL 查询
- c++ - 为什么要调用复制构造函数?
- javascript - 将用户批量添加到语音频道
- java - zuul限速和hystrix隔离策略有什么关系?