To achieve this in PostgreSQL, you can use a recursive Common Table Expression (CTE) to identify chains of entries where the starttime of the next entry is less than or equal to the endtime of the current entry. Each chain should be counted as a single entry. Here’s how you can write the query:
WITH RECURSIVE chain_cte AS (
-- Base case: Select all entries that are not referenced by any other entry
SELECT
id_1,
id_2,
starttime,
endtime,
1 AS chain_id,
ROW_NUMBER() OVER (ORDER BY starttime) AS base_row
FROM
your_table
WHERE
NOT EXISTS (
SELECT 1
FROM your_table t2
WHERE t2.starttime <= your_table.endtime
AND t2.id_1 = your_table.id_1
AND t2.id_2 = your_table.id_2
AND t2.endtime > your_table.endtime
)
UNION ALL
-- Recursive case: Join entries that form a chain
SELECT
t.id_1,
t.id_2,
t.starttime,
t.endtime,
c.chain_id,
c.base_row
FROM
your_table t
INNER JOIN
chain_cte c
ON
t.starttime <= c.endtime
AND t.id_1 = c.id_1
AND t.id_2 = c.id_2
AND t.endtime > c.endtime
)
SELECT
COUNT(DISTINCT chain_id) AS chain_count
FROM
chain_cte;
Explanation:
-
Base Case: The base case selects entries that are not part of any chain (i.e., entries that are not followed by another entry with a starttime within their endtime). These are considered the starting points of chains.
-
Recursive Case: The recursive part joins entries that form a chain by checking if the starttime of the next entry is within the endtime of the current entry.
-
Counting Chains: Finally, the outer query counts the distinct chain_id values, which represent the number of unique chains.
Notes:
- Replace
your_table with the actual name of your table.
- The
ROW_NUMBER() in the base case ensures that the recursion has a deterministic order, which is important for the recursive CTE to work correctly.
- This approach assumes that chains are formed based on both
id_1 and id_2. If chains are only based on one of these IDs, adjust the join conditions accordingly.
This query will give you the number of distinct chains in your table, where each chain is counted as a single entry.