Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Permintaan untuk menggabungkan catatan temporal berkelanjutan

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        

Anda dapat menggunakan tabel angka daripada menggunakan master..spt_values .



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Kode Kerangka Entitas Pertama dan Urutan SQL Server 2012

  2. SQL Server dan celah di kolom Identitas

  3. Cara Setup Database Mail di SQL Server (SSMS)

  4. Mengembalikan Daftar Email yang Dikirim dari SQL Server Database Mail (T-SQL)

  5. Penyebaran LocalDB pada PC klien