Count days between two dates, excluding weekends (MySQL only) - mysql

I need to calculate the difference (in days) between two dates in MySQL excluding weekends (Saturday and Sunday). That is, the difference in days minus the number of Saturday and Sunday in between.
At the moment, I simply count the days using:
SELECT DATEDIFF('2012-03-18', '2012-03-01')
This return 17, but I want to exclude weekends, so I want 12 (because the 3rd and 4th, 10th and 11th and 17th are weekends days).
I do not know where to start. I know about the WEEKDAY() function and all related ones, but I do not know how to use them in this context.

Simply try it using a simple function :
CREATE FUNCTION TOTAL_WEEKDAYS(date1 DATE, date2 DATE)
RETURNS INT
RETURN ABS(DATEDIFF(date2, date1)) + 1
- ABS(DATEDIFF(ADDDATE(date2, INTERVAL 1 - DAYOFWEEK(date2) DAY),
ADDDATE(date1, INTERVAL 1 - DAYOFWEEK(date1) DAY))) / 7 * 2
- (DAYOFWEEK(IF(date1 < date2, date1, date2)) = 1)
- (DAYOFWEEK(IF(date1 > date2, date1, date2)) = 7);
Test :
SELECT TOTAL_WEEKDAYS('2013-08-03', '2013-08-21') weekdays1,
TOTAL_WEEKDAYS('2013-08-21', '2013-08-03') weekdays2;
Result :
| WEEKDAYS1 | WEEKDAYS2 |
-------------------------
| 13 | 13 |

Illustration:
mtwtfSSmtwtfSS
123456712345 one week plus 5 days, you can remove whole weeks safely
12345------- you can analyze partial week's days at start date
-------12345 or at ( end date - partial days )
Pseudocode:
#S = start date
#E = end date, not inclusive
#full_weeks = floor( ( #E-#S ) / 7)
#days = (#E-#S) - #full_weeks*7 OR (#E-#S) % 7
SELECT
#full_weeks*5 -- not saturday+sunday
+IF( #days >= 1 AND weekday( S+0 )<=4, 1, 0 )
+IF( #days >= 2 AND weekday( S+1 )<=4, 1, 0 )
+IF( #days >= 3 AND weekday( S+2 )<=4, 1, 0 )
+IF( #days >= 4 AND weekday( S+3 )<=4, 1, 0 )
+IF( #days >= 5 AND weekday( S+4 )<=4, 1, 0 )
+IF( #days >= 6 AND weekday( S+5 )<=4, 1, 0 )
-- days always less than 7 days

Below function will give you the Weekdays, Weekends, Date difference with proper results:
You can call the below function like,
select getWorkingday('2014-04-01','2014-05-05','day_diffs');
select getWorkingday('2014-04-01','2014-05-05','work_days');
select getWorkingday('2014-04-01','2014-05-05','weekend_days');
DROP FUNCTION IF EXISTS PREPROCESSOR.getWorkingday;
CREATE FUNCTION PREPROCESSOR.`getWorkingday`(d1 datetime,d2 datetime, retType varchar(20)) RETURNS varchar(255) CHARSET utf8
BEGIN
DECLARE dow1, dow2,daydiff,workdays, weekenddays, retdays,hourdiff INT;
declare newstrt_dt datetime;
SELECT dd.iDiff, dd.iDiff - dd.iWeekEndDays AS iWorkDays, dd.iWeekEndDays into daydiff, workdays, weekenddays
FROM (
SELECT
dd.iDiff,
((dd.iWeeks * 2) +
IF(dd.iSatDiff >= 0 AND dd.iSatDiff < dd.iDays, 1, 0) +
IF (dd.iSunDiff >= 0 AND dd.iSunDiff < dd.iDays, 1, 0)) AS iWeekEndDays
FROM (
SELECT dd.iDiff, FLOOR(dd.iDiff / 7) AS iWeeks, dd.iDiff % 7 iDays, 5 - dd.iStartDay AS iSatDiff, 6 - dd.iStartDay AS iSunDiff
FROM (
SELECT
1 + DATEDIFF(d2, d1) AS iDiff,
WEEKDAY(d1) AS iStartDay
) AS dd
) AS dd
) AS dd ;
if(retType = 'day_diffs') then
set retdays = daydiff;
elseif(retType = 'work_days') then
set retdays = workdays;
elseif(retType = 'weekend_days') then
set retdays = weekenddays;
end if;
RETURN retdays;
END;
Thank You.
Vinod Cyriac.
Bangalore

IT my helpful to you
The bellow logic only show the how many days
like
sun mon
1 2 .....................
DELIMITER $$
DROP FUNCTION IF EXISTS `xx`.`get_weekday` $$
CREATE FUNCTION `xx`.`get_weekday` (first_date date, last_date date, curr_week_day int) RETURNS INT
BEGIN
DECLARE days_tot int;
DECLARE whole_weeks int;
DECLARE first_day int;
DECLARE last_day int;
SET whole_weeks = FLOOR(DATEDIFF(last_date,first_date)/7) ;
SET first_day = WEEKDAY(first_date) ;
SET last_day = WEEKDAY(last_date) ;
IF curr_week_day BETWEEN first_day AND last_day
AND last_day > first_day
OR ( curr_week_day BETWEEN last_day AND first_day
AND last_day < first_day )
THEN SET days_tot = whole_weeks + 1;
ELSE SET days_tot = whole_weeks ;
END IF;
RETURN days_tot;
END $$
DELIMITER ;
SELECT
`xx`.`get_weekday` ('2009-01-01', '2009-07-20', 0) as mo,
`xx`.`get_weekday` ('2009-01-01', '2009-07-20', 1) as tu,
`xx`.`get_weekday` ('2009-01-01', '2009-07-20', 2) as we,
`xx`.`get_weekday` ('2009-01-01', '2009-07-20', 3) as th,
`xx`.`get_weekday` ('2009-01-01', '2009-07-20', 4) as fr,
`xx`.`get_weekday` ('2009-01-01', '2009-07-20', 5) as sa,
`xx`.`get_weekday` ('2009-01-01', '2009-07-20', 6) as su;
Table based query
ip:
Weekday count
2 10
3 5
SELECT WEEKDAY( `req_date_time` ) AS weekday, COUNT( id ) AS id
FROM `ddd`
WHERE (
`req_date_time` >= '2014-12-01'
AND `req_date_time` <= '2014-12-31'
)
AND WEEKDAY( `req_date_time` ) != '1'
GROUP BY WEEKDAY( `req_date_time` )

You can use a dates table:
tbl_dates
dow is 'day of week' in my table. Then your query looks like this:
SELECT Count(theDate) AS numWeekDays
FROM tbl_dates
WHERE theDate >[startDate] And theDate <=[endDate] AND dow <> 1 AND dow <> 7;
In this case, 1 and 7 are Sunday, Saturday, respectively (which is the default) and, of course, you can nest that into another query if you need to calculate this for many startDate(s) and endDate(s).

Related

In mysql How to find number of sundays in a month

In mysql how to find number of sundays in month by usnig month in where clause
Ex:
month(log_date)=month(now());
month(log_date) = 12;
output: 5 sundays
Possible way to do it which avoids using any tables. This finds the number of days in the month, and depending on that and what day of the week the last day is then it just returns a value
SELECT CASE DAYOFMONTH(LAST_DAY(NOW()))
WHEN 31 THEN
CASE DAYOFWEEK(LAST_DAY(NOW()))
WHEN 1 THEN 5
WHEN 2 THEN 5
WHEN 3 THEN 5
ELSE 4
END
WHEN 30 THEN
CASE DAYOFWEEK(LAST_DAY(NOW()))
WHEN 1 THEN 5
WHEN 2 THEN 5
ELSE 4
END
WHEN 29 THEN
CASE DAYOFWEEK(LAST_DAY(NOW()))
WHEN 1 THEN 5
ELSE 4
END
ELSE 4
END
SQL query for get total sunday in given month from DB
USE BETWEEN :- BETWEEN operator selects values within a given range.
Note :- DAYOFWEEK actually returns 1 for Sunday
SELECT count(*) AS total_sunday FROM `table` WHERE DAYOFWEEK(`date`) = 1 BETWEEN '2017-11-01' AND '2017-11-30';
In mysql just copy and paste the query given below. It will give you number of Sundays in current month.
WITH RECURSIVE offdays as(
SELECT
LAST_DAY(CURDATE()-INTERVAL 1 MONTH) + INTERVAL 1 DAY AS `Date`,
DAYNAME(LAST_DAY(CURDATE()-INTERVAL 1 MONTH) + INTERVAL 1 DAY) AS `DayName`
UNION ALL
SELECT `Date` + INTERVAL 1 DAY, DAYNAME(`Date` + INTERVAL 1 DAY)
FROM offdays WHERE `DATE` < LAST_DAY(CURDATE())
) SELECT count(*) FROM offdays where DAYNAME(DATE) = 'Sunday';
you will get number of sundays in current month. Just replace the CURDATE() with any date. The query will give you the number of Sundays of the month of the date supplied.
Try this function, you use like
count_days_in_month($date_month,$day_idx);
$day_idx is 1 - 7 where Sunday is 1, Saturday is 7
eg.
select count_days_in_month('2020-02-01',1);
delimiter //
create or replace function count_days_in_month(input_date DATE,dayindex INT)
returns INT
DETERMINISTIC
BEGIN
declare start_day_idx INT default (select dayofweek( date_sub(input_date,INTERVAL (DAYOFMONTH(input_date)-1) DAY )) from dual);
declare days_in_month INT default (SELECT dayofmonth(LAST_DAY(input_date)));
declare days_over_28 INT default (days_in_month-28);
if days_in_month > 28 then
if (days_over_28 > (dayindex-start_day_idx)) and ((dayindex-start_day_idx) >= 0) then
return 5;
else
return 4;
end if;
else
return 4;
end if;
END//
Eg to test the count of all days in a month:
select
count_days_in_month('2020-02-01',1) 'Sun',
count_days_in_month('2020-02-01',2) 'Mon',
count_days_in_month('2020-02-01',3) 'Tue',
count_days_in_month('2020-02-01',4) 'Wed',
count_days_in_month('2020-02-01',5) 'Thur',
count_days_in_month('2020-02-01',6) 'Fri',
count_days_in_month('2020-02-01',7) 'Sat'
from
dual;//

It does not work collection queries with the condition

I need to bring to the customer a discount depending on how long it took a training course.
To find out the date of passage must first know the group ID to which the client belongs.
When I know Id of group, I can find date when started training course.
And then, determined the size of discounts by finded date
Here's a script that works great in MS SQL, but in MySql it doesn't works.
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetBonus`(
idStudent CHAR(36)
)
BEGIN
IF (SELECT COUNT(*) FROM (SELECT IdGroupe FROM GroupeStudent WHERE IdStudent = idStudent) groupeCourse) = 1 THEN
BEGIN
DECLARE CourseGroupeDate datetime;
SET CourseGroupeDate = (SELECT Date FROM CourseGroupe WHERE Id = (SELECT IdGroupe FROM GroupeStudent WHERE IdStudent = idStudent));
IF (CourseGroupeDate - INTERVAL NOW() MONTH) < 3 AND
(CourseGroupeDate - INTERVAL NOW() MONTH) > 0
THEN SELECT * FROM Discounts WHERE Id = '00000000-0000-0000-0000-000000000000';
ELSEIF (CourseGroupeDate - INTERVAL NOW() MONTH) < 6 AND
(CourseGroupeDate - INTERVAL NOW() MONTH) > 3
THEN SELECT * FROM Discounts WHERE Id = '00000000-0000-0000-0000-000000000001';
ELSEIF (CourseGroupeDate - INTERVAL NOW() MONTH) < 12 AND
(CourseGroupeDate - INTERVAL NOW() MONTH) > 6
THEN SELECT * FROM Discounts WHERE Id = '00000000-0000-0000-0000-000000000002';
END IF;
END;
END IF;
END
CREATE PROCEDURE `GetBonus`(
idStudent CHAR(36)
)
BEGIN
IF (SELECT COUNT(groupeCourse.IdGroupe) FROM (SELECT IdGroupe FROM GroupeStudent WHERE GroupeStudent.IdStudent = idStudent) groupeCourse) = 1 THEN
BEGIN
SET #CourseGroupeDate := (SELECT Date FROM CourseGroupe WHERE Id = (SELECT GroupeStudent.IdGroupe FROM GroupeStudent WHERE GroupeStudent.IdStudent = idStudent));
IF (TIMESTAMPDIFF(MONTH, #CourseGroupeDate, now())) < 3 AND
(TIMESTAMPDIFF(MONTH, #CourseGroupeDate, now())) > 0
THEN SELECT * FROM Discounts WHERE Id = '00000000-0000-0000-0000-000000000000';
ELSEIF (TIMESTAMPDIFF(MONTH, #CourseGroupeDate, now())) < 6 AND
(TIMESTAMPDIFF(MONTH, #CourseGroupeDate, now())) > 3
THEN SELECT * FROM Discounts WHERE Id = '00000000-0000-0000-0000-000000000001';
ELSEIF (TIMESTAMPDIFF(MONTH, #CourseGroupeDate, now())) < 12 AND
(TIMESTAMPDIFF(MONTH, #CourseGroupeDate, now())) > 6
THEN SELECT * FROM Discounts WHERE Id = '00000000-0000-0000-0000-000000000002';
END IF;
END;
END IF;
END
All in the details , for example , it was necessary to specify the table name about the field GroupeStudent.IdStudent = idStudent

Insert into MySQL table all Sundays and Saturdays from current year

I have this tiny table with just "fecha" field in it.
I need a MySQL query that inserts every sunday and saturday of the year to the table.
My own research got me to the point where i know i need to do something like this:
DECLARE diaRecorrido date();
SET diaRecorrido = date(now());
WHILE DATEPART(WEEKDAY,diaRecorrido) = 1 or DATEPART(WEEKDAY,diaRecorrido) = 7
BEGIN
INSERT INTO feriados (fecha)
VALUES (diaRecorrido)
IF diaRecorrido=2017/01/01
THEN
LEAVE lazo;
END IF;
END;
Any guidance is much apreciated!
I think, you should use DAYOFWEEK()
create PROCEDURE generateSundayAndSaturday()
BEGIN
DECLARE _now DATETIME;
DECLARE _endYear DATETIME;
SET _endYear = DATE_FORMAT(NOW() + INTERVAL 1 YEAR ,'%Y-01-01');
SELECT now() into _now from dual;
while _now < _endYear DO
if DAYOFWEEK(_now) = 7 THEN -- Saturday
-- insert into
SET _now = _now + INTERVAL 1 DAY;
ELSEIF DAYOFWEEK(_now) = 1 THEN -- Sunday
-- insert into
SET _now = _now + INTERVAL 6 DAY;
ELSE
SET _now = _now + INTERVAL 1 DAY;
END IF;
END WHILE;
END;
You could create a numbers table and then select from it the days of the year which you wish to keep:
DECLARE #Date1 DATE, #Date2 DATE
SET #Date1 = '20160101'
SET #Date2 = '20161231'
INSERT INTO feriados
SELECT DATEADD(DAY,number+1,#Date1) [Date]
FROM master..spt_values
WHERE type = 'P' AND
DATEADD(DAY,number+1,#Date1) < #Date2 AND
(DATEPART(WEEKDAY, DATEADD(DAY,number+1,#Date1)) = 1 OR
DATEPART(WEEKDAY, DATEADD(DAY,number+1,#Date1)) = 7)
This is MS SQL (t-sql) query. I think you can fix small syntax differences for MySQL.
declare #thisYear datetime=cast(year(getdate()) as varchar)+'-01-01',
#newyear datetime=cast(year(getdate())+1 as varchar)+'-01-01'
declare #frstSat datetime, #frstSun datetime
select #frstSat= dateadd(dd,7-DATEPART(weekday,#thisYear),#thisYear) ,
#frstSun= case DATEPART(weekday,#thisYear)
when 1 then #thisYear --if 1/1 is Sunday
else dateadd(dd,8-DATEPART(weekday,#thisYear),#thisYear) end
;with sat as (
select #frstSat dt,'Sat' WkDay
union all
select dateadd(dd,7,dt),'Sat' WkDay
from sat
where dateadd(dd,7,dt)<#newyear
)
,sun as (
select #frstSun dt,'Sun' WkDay
union all
select dateadd(dd,7,dt),'Sun' WkDay
from sun
where dateadd(dd,7,dt)<#newyear
)
--insert mytable
select * from sat
union
select * from sun
order by dt

How to calculate number of Sundays between two dates using mysql

I need to find number of Sundays between two dates using mysql. I know how to do it using PHP But i need it to be calculated using mysql.
SET #START_DATE = '2014-01-22';
SET #END_DATE = '2014-06-29';
SELECT
ROUND((
(unix_timestamp(#END_DATE) - unix_timestamp(#START_DATE) ) /(24*60*60)
-7+WEEKDAY(#START_DATE)-WEEKDAY(#END_DATE)
)/7)
+ if(WEEKDAY(#START_DATE) <= 6, 1, 0)
+ if(WEEKDAY(#END_DATE) >= 6, 1, 0) as Sundays;
Solution consist of 2 parts:
counts number of full weeks (ROUND part), obviously you'll have 7 Sundays in 7 weeks.
count days that are included into the not full week parts (first or last)
If you'll need to use it more than once you can wrap it into the function:
DROP function IF EXISTS `count_weekdays`;
DELIMITER $$
CREATE FUNCTION `count_weekdays` (startDate date, endDate date, wd int)
RETURNS INTEGER
BEGIN
RETURN ROUND((
(unix_timestamp(endDate) - unix_timestamp(startDate) ) /(24*60*60)
-7+WEEKDAY(startDate)-WEEKDAY(endDate)
)/7)
+ if(WEEKDAY(startDate) <= wd, 1, 0)
+ if(WEEKDAY(endDate) >= wd, 1, 0);
END$$
DELIMITER ;
Then you will be able to use it like this:
SET #START_DATE = '2018-07-03';
SET #END_DATE = '2018-07-28';
select
count_weekdays(#START_DATE, #END_DATE, 6) as Sundays,
count_weekdays(#START_DATE, #END_DATE, 5)
+ count_weekdays(#START_DATE, #END_DATE, 6) as weekends;
Where 6 ~ number of weekday stands for Sunday, 5 ~ Saturday.
http://sqlfiddle.com/#!2/d41d8/50695
Maybe there will be no code on this link someday so I posted it here.
the upper link will show the number of the day and with date of the sundays. if you want to find any other day change the 1 at last to 2 for monday
select DATE_ADD('2012-12-15', INTERVAL ROW DAY) as Date,
row+1 as DayOfMonth from (
SELECT #row := #row + 1 as row FROM
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6) t1,
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6) t2,
(SELECT #row:=-1) t3 limit 31
) b
where
DATE_ADD('2012-12-01', INTERVAL ROW DAY)
between '2012-12-01' and '2012-12-31'
and
DAYOFWEEK(DATE_ADD('2012-12-01', INTERVAL ROW DAY))=1
Does this work...
SELECT FLOOR(
(DATEDIFF(
'#enddate'
,'#startdate' + INTERVAL
LENGTH(SUBSTRING_INDEX('654321',WEEKDAY('#startdate'),1))
DAY) + 1)/7) + 1 x;
SELECT a.StartDate, a.EndDate,
(DAY(EndDate - StartDate) / 7)
+ iif(DAY(EndDate - StartDate)%7 + DATEPART(DW, StartDate) > 8 , 1, 0)
Sundays FROM
(SELECT GETDATE() StartDate, DATEADD(DAY, 11, GETDATE()) EndDate) a
This is useful for multiple start and end dates in a table.
no need of variables and loops!
How it works: determines the number of full weeks between start and end date,
determines the days less than a week and add with the start day index(1,2,3,4,5,6,7) if that value Greater than count 8(means which is Sunday !)
For Sunday week day index is 1, day 8 is nothing but index 1.
SELECT COUNT(*) FROM table_name
WHERE column BETWEEN 'start_date' AND 'end_date'
AND WEEKDAY(date) = 6;
Refer this, mysql have a function dayofweek, you can easily calculate starting week day and after that divide the number of days with 7:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofweek
OR
SELECT COUNT(*) FROM table_name
WHERE date_column_of_table_name BETWEEN '2013-01-11' AND '2013-03-01'
AND WEEKDAY(date_column_of_table_name) = 6
Try this
select count(DAYNAME(your_date_field)='Sunday') as sunday from tbl_name where your_date_field between 'date1' AND 'date2'

displaying dates of entire week starting day as saturday

I have got the code in this site for all weeks in a year as follows,i should populate week dates, starting date as saturday and end date as friday. when the week is finished it should enter to the next week with dates.
how could i achieve this please help me.
DECLARE #Year INT=2013;
DECLARE #start DATE;
--DECLARE #WK INT=2
SET #start = DATEADD(YEAR, #Year-1900, 0);
;WITH n AS
(
SELECT TOP (366) -- in case of leap year
TDate = DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY name)-1, #start)
FROM sys.all_objects
),
x AS
(
SELECT md = MIN(TDate) FROM n
WHERE DATEPART(WEEKDAY, TDate) = 7 -- assuming DATEFIRST is SATURDAY
),
y(TDate,wk) AS
(
SELECT n.TDate, ((DATEPART(DAYOFYEAR,n.TDate)-
DATEDIFF(DAY, #start,x.md)-1)/7)+1
FROM n CROSS JOIN x
WHERE n.TDate >= x.md
AND n.TDate < DATEADD(YEAR, 1, #start)
)
SELECT [date] = TDate, [week] = wk
FROM y WHERE wk < 53
ORDER BY [date];
Not really sure what you're asking, but based on your query above this will give week numbers, based on Saturday being the first day of the week, for 2013:
DECLARE #Year INT=2013;
DECLARE #start DATE;
SET #start = DATEADD(YEAR, #Year-1900, 0);
SET DATEFIRST 6; -- Set start of week as Saturday
WITH n AS
(
SELECT TOP (366) -- in case of leap year
TDate = DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY name)-1, #start)
FROM sys.all_objects
)
select TDate
, DATEPART(WEEK,TDate)
from n
where year(TDate) = 2013;
Edit:
So based on the various comments and answers I think what is required here is, for a given day, return all days in that same week, with Saturday as the first day of the week. So something like this:
set datefirst 6; -- make sure first day of week is Saturday
declare #date date = getdate(); -- change date as required here
with daysOfWeek as
(
select [date] = dateadd(dd, -datepart(dw, #date) + 1, #date)
union all
select [date] = dateadd(dd, 1, [date])
from daysOfWeek
where [date] < dateadd(dd, -datepart(dw, #date) + 7, #date)
)
select [date], dayOfWeek = datename(dw, [date])
from daysOfWeek
Which gives results:
I think this is what's required here?
Second edit:
First, create the function:
create function dbo.weekDates (#date date)
returns #dates table ([date] date, [dayofweek] varchar(9))
as
begin
with daysOfWeek as
(
select [date] = dateadd(dd, -datepart(dw, #date) + 1, #date)
union all
select [date] = dateadd(dd, 1, [date])
from daysOfWeek
where [date] < dateadd(dd, -datepart(dw, #date) + 7, #date)
)
insert into #dates ([date], [dayofweek])
select [date], [dayOfWeek] = datename(dw, [date])
from daysOfWeek;
return
end
go
Using the function:
set datefirst 6 -- Set Saturday as first day of week
select * from dbo.weekDates (getdate()) -- Change input parameter as required
I HAVE ACHIEVED TO DISPLAY THE WEEK DATES BUT IT IS DISPLAYING THE NEXT WEEK DATES I WANT TO DISPLAY THE CURRENT WEEK DATES, HERE START DAY IS SATURDAY AND END DAY IS FRIDAY
ALTER FUNCTION GetCurrentWeek()
RETURNS #TWeek TABLE (TWeek NVARCHAR(20))
AS
BEGIN
DECLARE #Year INT= DATEPART(YEAR,GETDATE());
DECLARE #start DATE;
SET #start = DATEADD(YEAR, #Year-1900, 0);
;WITH n AS
(
SELECT TOP (366) -- in case of leap year
TDate = DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY name)-1, #start)
FROM sys.all_objects
),
x AS
(
SELECT md = MIN(TDate) FROM n
WHERE DATEPART(WEEKDAY, TDate) = 7 -- assuming DATEFIRST is SATURDAY
),
y(TDate,wk) AS
(
SELECT n.TDate, ((DATEPART(DAYOFYEAR, n.TDate)
- DATEDIFF(DAY, #start, x.md)-1)/7) + 1
FROM n CROSS JOIN x
WHERE n.TDate >= x.md
AND n.TDate < DATEADD(YEAR, 1, #start)
)
INSERT #TWeek
SELECT [date] = TDate
FROM y WHERE wk =DATEPART(wk, GetDate())
ORDER BY [date];
RETURN;
END