我试图找到系统处于特定状态的所有时间段。状态登录到表中。数据的一个例子如下:
Time - State
12:00 - 1
12:01 - 1
12:02 - 1
12:03 - 1
12:04 - 0
12:05 - 0
12:06 - 0
12:07 - 1
12:08 - 1
我希望看到的结果是:
Start - End - State
12:00 - 12:03 - 1
12:04 - 12:06 - 0
12:07 - 12:08 - 1
是否有任何预定义的功能来查找转换记录?
答案 0 :(得分:2)
这样的事情应该有效:
SELECT "State",
MIN("Time") AS Start,
MAX("Time") AS End
FROM (
SELECT "Time", "State",
ROW_NUMBER() OVER (ORDER BY "Time") -
ROW_NUMBER() OVER (PARTITION BY "State" ORDER BY "Time") AS grp
FROM mytable) AS t
GROUP BY "State", grp
内部查询使用标准技术来识别具有相同State
值的连续记录的 islands 。外部查询使用计算列grp
到GROUP BY
并获取每个岛的Start
,End
值。