Skip to main content
replaced http://stackoverflow.com/ with https://stackoverflow.com/
Source Link
added 152 characters in body
Source Link
ErikE
  • 4.3k
  • 4
  • 28
  • 39

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)

You can do this as a simple subtraction of DENSE_RANK() operations (or if your dates are guaranteed unique then you can use ROW_NUMBER() in both places for a less expensive query):

WITH IdTypes AS (
   SELECT
      date,
      id_type,
      Dense_Rank() OVER (ORDER BY date)
         - Dense_Rank() 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

You can do this as a simple subtraction of ROW_NUMBER() operations (or if your dates are not unique, though still unique per id_type, then you can use DENSE_RANK() instead, though it will be a more expensive query):

WITH IdTypes AS (
   SELECT
      date,
      id_type,
      Row_Number() OVER (ORDER BY date)
         - Row_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 DENSE_RANK version)

added 115 characters in body
Source Link
ErikE
  • 4.3k
  • 4
  • 28
  • 39

You can do this as a simple subtraction of DENSE_RANK() operations (or if your dates are guaranteed unique then you can use ROW_NUMBER() in both places for a less expensive query):

You can do this as a simple subtraction of DENSE_RANK() operations:

You can do this as a simple subtraction of DENSE_RANK() operations (or if your dates are guaranteed unique then you can use ROW_NUMBER() in both places for a less expensive query):

added 140 characters in body
Source Link
ErikE
  • 4.3k
  • 4
  • 28
  • 39
Loading
added 291 characters in body
Source Link
ErikE
  • 4.3k
  • 4
  • 28
  • 39
Loading
Source Link
ErikE
  • 4.3k
  • 4
  • 28
  • 39
Loading