-3

I do cant get the begin and end week between two dates in Sql Server? for example:

    begin       end
    2016-04-25  2016-05-01
    2016-05-02  2016-05-08
    2016-05-09  2016-05-15
    2016-05-16  2016-05-22
    2016-05-23  2016-05-29
    2016-05-30  2016-06-05
...

Regards!

Pரதீப்
  • 91,748
  • 19
  • 131
  • 172

4 Answers4

0

SQL has the DATEDIFF(datepart,startdate,enddate) function for this purpose.

Example:

SELECT DATEDIFF(day,'2014-06-05','2014-08-05') AS DiffDate

results in

61

Learn more about DATEFIFF here

Luca Schimweg
  • 747
  • 5
  • 18
0

use DATEDIFF() function in SQL Server

elfico
  • 450
  • 1
  • 6
  • 13
0

You need a date table to do this

Declare @start_date datetime = '2016-04-25'
        @end_date datetime = '2016-06-05'

SELECT Min(dt) AS week_start, 
       Max(dt) AS week_end 
FROM   dates_table 
WHERE  date_col > @start_date 
       AND date_col < @end_date 
GROUP  BY Datepart(week, dt), 
          Year(dt) 
ORDER  BY Datepart(week, dt), 
          Year(dt) 

To create a date table and populate dates, Here is few question about generating dates between range of dates

  1. How to generate a range of dates in SQL Server

  2. Generate Dates between date ranges

Community
  • 1
  • 1
Pரதீப்
  • 91,748
  • 19
  • 131
  • 172
0

Try this :

DECLARE @d1 DATE = '2016-04-20' , @d2 DATE = '2016-06-07'
, @mon1 DATE
;WITH 
sunA AS (
  SELECT k=1, dt = @d1, dn = datename(dw,@d1)
  UNION ALL 
  SELECT k=k+1, dt = DATEADD(d,1,dt), dn = datename(dw,DATEADD(d,1,dt))
  FROM sunA 
  WHERE k<7
) 
  SELECT TOP 1 @mon1 = dt 
  FROM sunA
  WHERE dn = 'Monday'
  ORDER BY k

DECLARE @weeks TABLE(d1 DATE, d2 DATE)
WHILE @mon1 >= @d1 AND DATEADD(d, 6, @mon1) <= @d2
BEGIN
  INSERT INTO @weeks SELECT @mon1, DATEADD(d, 6, @mon1)
  SET @mon1 = DATEADD(d, 7, @mon1)
END

SELECT * FROM @weeks

-- OUTPUT
d1          d2
2016-04-25  2016-05-01
2016-05-02  2016-05-08
2016-05-09  2016-05-15
2016-05-16  2016-05-22
2016-05-23  2016-05-29
2016-05-30  2016-06-05
leoinfo
  • 7,860
  • 8
  • 36
  • 48