【发布时间】:2016-09-02 07:28:02
【问题描述】:
假设数据结构的类型
stock_name, action, start_date, end_date
google, growing, 1, 2
google, growing, 2, 3
google, falling, 3, 4
google, growing, 4, 5
yahoo, growing, 1, 2
如何聚合它以合并连续的时间间隔?
输出如下:
stock_name, action, start_date, end_date
google, growing, 1, 3
google, falling, 3, 4
google, growing, 4, 5
yahoo, growing, 1, 2
我曾想过使用排名窗口函数用一个常数对连续的数字进行编号,然后按该常数和动作/名称进行分组,但我无法让它发挥作用,如下所示:
stock_name, action, start_date, end_date, rank
google, growing, 1, 2, 1
google, growing, 2, 3, 1
google, falling, 3, 4, 1
google, growing, 4, 5, 2
yahoo, growing, 1, 2, 1
如果这是Mysql,我很容易用变量解决它,但这在postgres中是不可能的。
可以有任意数量的连续间隔,因此不能选择自行加入预定的 nr 次。
解决方案的优雅(性能、可读性)很重要。
【问题讨论】:
-
连续时间间隔是否可以包含超过 2 条记录(例如 3、4、5)?
-
这对我来说实际上看起来像是一个空白和孤岛问题。
-
@AdrianBR
If this were Mysql, I would easily solve it with variables, but this is not possible in postgres- 在 postgres 中什么是不可能的? -
@AdrianBR 如果您需要用户定义的变量,请使用 postgres 过程语言
标签: sql postgresql gaps-and-islands