Postgres 发现转换
Postgres finding transitions
我正在尝试查找系统处于特定状态的所有时间段。状态登录到table。数据示例如下:
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
是否有任何预定义的函数来查找转换记录?
像这样的东西应该可以工作:
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
值的 岛 连续记录。外部查询使用计算列 grp
到 GROUP BY
并获取每个 island.
的 Start
、End
值
我正在尝试查找系统处于特定状态的所有时间段。状态登录到table。数据示例如下:
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
是否有任何预定义的函数来查找转换记录?
像这样的东西应该可以工作:
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
值的 岛 连续记录。外部查询使用计算列 grp
到 GROUP BY
并获取每个 island.
Start
、End
值