sql >> Database teknologi >  >> RDS >> Sqlserver

Forespørgsel om at flette kontinuerlige tidsmæssige poster

declare @T table
(
  id int,
  start_date datetime,
  end_date datetime
)

insert into @T values
(1,      '01/01/2011',   '01/10/2011'),
(2,      '01/11/2011',   '01/20/2011'),
(3,      '01/25/2011',   '02/01/2011'),
(4,      '02/10/2011',   '02/15/2011'),
(5,      '02/16/2011',   '02/27/2011')

select row_number() over(order by min(dt)) as new_id,
       min(dt) as start_date,
       max(dt) as end_date
from (
      select dateadd(day, N.Number, start_date) as dt,
             dateadd(day, N.Number - row_number() over(order by dateadd(day, N.Number, start_date)), start_date) as grp
      from @T
        inner join master..spt_values as N
          on N.number between 0 and datediff(day, start_date, end_date) and
             N.type = 'P'
     ) as T
group by grp
order by new_id        

Du kan bruge en taltabel i stedet for at bruge master..spt_values .



  1. Hvad hedder rør?

  2. NOT NULL begrænsning over et sæt kolonner

  3. Hent alle fremmednøgler ved hjælp af JDBC

  4. ER_CON_COUNT_ERROR:For mange forbindelser fejl i node-mysql