Skip to content
Advertisement

Need to group records by consecutive date SQL

I’m building a query in order to build consecutive dates which is

but I’m facing a problem with two things.

  1. query is too expensive when files are big.

  2. if the dates are something like

    startdate enddate ‘2019-08-01’ ‘2019-09-30’ ‘2019-10-01’ ‘2019-10-31’

Then the query will not group the dates and I need it to be smart enough to solve this kind of cases.

Any help would be nice,

Thanks.

Advertisement

Answer

I undersand that you want to group together records that have the same sgid and metric and that are adjacent (ie next record starts one day after the end of the current record).

Here is a gaps and island solution that uses window sum to define the groups:

For your sample data, where all three records are adjacent, this produces:

sgid | metric | startdate               | enddate                
:--- | :----- | :---------------------- | :----------------------
2177 | 515818 | 2019-07-01 00:00:00.000 | 2019-09-30 00:00:00.000

Demo on DB Fiddle

Note that the query uses SQL Server date functions (which I suspect that you are using): alternatives exists in other databases.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement