SELECT *
FROM (
SELECT *, LAG(stop) OVER (ORDER BY start) AS start_anarchy, start AS stop_anarchy
FROM (
SELECT *
FROM reigns
UNION ALL
VALUES (NULL::INTEGER, NULL::INTEGER)
) q
) q
WHERE start_anarchy IS DISTINCT FROM stop_anarchy
This will also show the years before the first ruler and after the last one.
From the original table again i'm trying to get an output table where i would have the centuries in the first column and in the second column the average time of all the people in charge in that century.
SELECT TRUNC(start - 1, -2) AS century, AVG(stop - start) AS avg_reign
FROM q
GROUP BY
TRUNC(start - 1, -2)
The centuries are calculated according the the start of the reign, and 00
years are the last years of previous centuries (e. g. Constantine II
would be a IX
century king).