Split row based on start end date SQL Server

爷,独闯天下 提交于 2019-12-05 22:33:48

This is how you can do it using a recursive CTE:

;with CTE as (
  select package, startDate, EndDate from data
  union all
  select package, dateadd(month, 12, startDate), EndDate
  from CTE where EndDate > dateadd(month, 12, startDate)
)

select 
  package,
  startdate,
  case when enddate <= dateadd(month, 12, startdate)
    then enddate else dateadd(day, -1, dateadd(month, 12, startdate)) end
    as enddate
From
  CTE 
order by package, startdate

The CTE will take the rows from the table, and then recursively select new row if the startdate + 12 month is less than the end date. The select outside the CTE will determine which value from the row to be used, startdate + 12 months or end date.

SQL Fiddle: http://sqlfiddle.com/#!6/5bfbf/4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!