You can do this as a simple subtraction of DENSE_RANKROW_NUMBER()
operations (or if your dates are guaranteednot unique, though still unique per id_type
, then you can use ROW_NUMBERDENSE_RANK()
in both places forinstead, though it will be a lessmore expensive query):
WITH IdTypes AS (
SELECT
date,
id_type,
Dense_RankRow_Number() OVER (ORDER BY date)
- Dense_RankRow_Number() OVER (PARTITION BY id_type ORDER BY date)
AS Seq
FROM
tmp
)
SELECT
Min(date) AS begin,
Max(date) AS end,
id_type
FROM IdTypes
GROUP BY id_type, Seq
ORDER BY begin
;
See this work at DB Fiddle
(or see the See this work at DB FiddleDENSE_RANK version)