I am trying to group data using Postgres.
Input Data:
My expectation result IF the output is 0, it will grouping with others, and IF output more than 0, it will grouping with other results, so we will know, time period for 0 output.
I am trying to group data using Postgres.
Input Data:
My expectation result IF the output is 0, it will grouping with others, and IF output more than 0, it will grouping with other results, so we will know, time period for 0 output.
This is a gaps and islands problem. One approach uses the difference in row numbers method:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Seq ORDER BY Datetime) rn1,
ROW_NUMBER() OVER (PARTITION BY Seq, Output > 0
ORDER BY Datetime) rn2
FROM yourTable
)
SELECT
Seq,
MIN(Datetime) AS MinDatetime,
MAX(Datetime) AS MaxDatetime,
SUM(Output) AS sum_output
FROM cte
GROUP BY
Seq,
Output > 0,
rn1 - rn2
ORDER BY
Seq,
MIN(Datetime);