How do you calculate the number of weeks between two dates?

前端 未结 2 360
南旧
南旧 2021-01-12 02:07

How do you calculate the number of weeks between two dates?

for example as follows

Declare @StartDate as DateTime = \"01 Jan 2009\";
Declare @EndDate         


        
2条回答
  •  臣服心动
    2021-01-12 02:36

    You may use the following function to retrives week's between two dates:

    CREATE FUNCTION [dbo].[fGetWeeksList]
    (
        @StartDate DATETIME 
       ,@EndDate DATETIME 
    )
    RETURNS 
    TABLE 
    AS
    RETURN
    (
    
    SELECT DATEADD(DAY,-(DATEPART(DW,DATEADD(WEEK, x.number, @StartDate))-2),DATEADD(WEEK, x.number, @StartDate)) as [StartDate]
          ,DATEADD(DAY,-(DATEPART(DW,DATEADD(WEEK, x.number + 1, @StartDate))-1) ,DATEADD(WEEK, x.number + 1, @StartDate)) AS [EndDate]
    FROM master.dbo.spt_values x
    WHERE x.type = 'P' AND x.number <= DATEDIFF(WEEK, @StartDate, DATEADD(WEEK,0,CAST(@EndDate AS DATE)))
    

提交回复
热议问题