how to get the start and end dates of all weeks between two dates in SQL server?

前端 未结 1 505
深忆病人
深忆病人 2020-12-01 19:28

I need to get all week start and end dates(weeks) between two dates and then run a query returning the number of records inserted in each of those weeks.

dec         


        
相关标签:
1条回答
  • 2020-12-01 20:23

    You can use a recursive CTE to generate the list of dates:

    ;with cte as
    (
      select @sDate StartDate, 
        DATEADD(wk, DATEDIFF(wk, 0, @sDate), 6) EndDate
      union all
      select dateadd(ww, 1, StartDate),
        dateadd(ww, 1, EndDate)
      from cte
      where dateadd(ww, 1, StartDate)<=  @eDate
    )
    select *
    from cte
    

    See SQL Fiddle with Demo.

    Then you can join this to your table, to return the additional details.

    0 讨论(0)
提交回复
热议问题