﻿<?xml version='1.0' encoding='UTF-8'?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>SQLServerCentral / SQL Server 2005 / SQL Server 2005 General Discussion  / Find number of weekdays(Monday,Tuesday..) between two dates monthwise / Latest Posts</title><generator>InstantForum.NET v2.9.0</generator><description>SQLServerCentral</description><link>http://www.sqlservercentral.com/Forums/</link><webMaster>notifications@sqlservercentral.com</webMaster><lastBuildDate>Thu, 23 May 2013 02:31:06 GMT</lastBuildDate><ttl>20</ttl><item><title>RE: Find number of weekdays(Monday,Tuesday..) between two dates monthwise</title><link>http://www.sqlservercentral.com/Forums/Topic513315-149-1.aspx</link><description>[quote][b]Stephen Yale (6/18/2008)[/b][hr].....How do I do it without using a cursor?.....[/quote]Here's one way:[code="sql"]CREATE FUNCTION [dbo].[IF_Calendar] (		@StartDate DATE,	@EndDate DATE,	@FirstWeekDay VARCHAR(10))RETURNS TABLE WITH SCHEMABINDING AS  RETURN (	-- inline tally table	WITH E1(N) AS (		SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL		SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL		SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1	),                          --10E+1 or 10 rows	E2(N) AS (SELECT 1 FROM E1 a CROSS JOIN E1 b), --10E+2 or 100 rows	E3(N) AS (SELECT 1 FROM E2 a CROSS JOIN E2 b), --10E+4 or 10,000 rows max	iTally AS ( -- generate sufficient rows to cover startdate to enddate inclusive		SELECT TOP(1+DATEDIFF(DAY,@StartDate,@EndDate)) 			rn = ROW_NUMBER() OVER(ORDER BY (SELECT NULL))-1		FROM E3	)	-- Do some date arithmetic 	SELECT		a.DateRange,		c.[Year],		c.[Month],		c.[DayOfMonth],		c.AbsWeekno,		c.[DayName],		d.Holiday 	FROM iTally	CROSS APPLY (SELECT DateRange = DATEADD(day,rn,@StartDate)) a	CROSS APPLY (VALUES ('Tuesday',1),('Wednesday',2),('Thursday',3),('Friday',4),('Saturday',5),('Sunday',6),('Monday',7)	) b (FirstWeekDay, FirstWeekdayOffset)	CROSS APPLY (		SELECT 			[Year] = YEAR(a.DateRange),			[Month] = MONTH(a.DateRange),			[DayOfMonth] = DAY(a.DateRange),			AbsWeekno	= DATEDIFF(day,FirstWeekdayOffset,a.DateRange)/7,			[DayName]	= DATENAME(weekday,a.DateRange)	) c	CROSS APPLY (		SELECT Holiday = CASE 			WHEN [Month] = 1  AND [DayOfMonth] = 1 THEN 'New Year' 			WHEN [Month] = 5  AND [DayOfMonth] &amp;gt;= 25 AND [DayName] = 'Monday' THEN 'Memorial Day' 			WHEN [Month] = 7  AND [DayOfMonth] = 4 THEN 'Independence Day' 			WHEN [Month] = 9  AND [DayOfMonth] &amp;lt;= 7 AND [DayName] = 'Monday' THEN 'Labor Day' 			WHEN [Month] = 11 AND [DayOfMonth] BETWEEN 22 AND 28 AND [DayName] = 'Thursday' THEN 'Thanksgiving Day' 			WHEN [Month] = 12 AND [DayOfMonth] = 25 THEN 'Christmas Day' 			ELSE NULL END	) d	WHERE b.FirstWeekDay = @FirstWeekDay)[/code]</description><pubDate>Thu, 18 Apr 2013 09:43:53 GMT</pubDate><dc:creator>ChrisM@Work</dc:creator></item><item><title>RE: Find number of weekdays(Monday,Tuesday..) between two dates monthwise</title><link>http://www.sqlservercentral.com/Forums/Topic513315-149-1.aspx</link><description>I would just wrap your code in () and use it as a type of derived table and average the counts like this...select MonthName, Dayname, Average(actualCount)from (SELECT CreationDate,DATENAME(month, CreationDate) as MonthName,DATENAME(dw, CreationDate) as DayName ,count(*) as ActualCountFROM LogBaseWhere CreationDate between @fromDate and @toDate group by CreationDate, DATENAME(month, CreationDate),DATENAME(dw, CreationDate)) as agroup by  MonthName, Dayname</description><pubDate>Thu, 18 Apr 2013 06:49:31 GMT</pubDate><dc:creator>Kevin Bernard</dc:creator></item><item><title>RE: Find number of weekdays(Monday,Tuesday..) between two dates monthwise</title><link>http://www.sqlservercentral.com/Forums/Topic513315-149-1.aspx</link><description>[quote][b]GSquared (6/9/2008)[/b][hr]For accurate counts of weekdays, I HIGHLY recommend a calendar table.  That way, you can include holidays, etc.[code]create table Calendar (Date datetime primary key,constraint CK_Date_NoTime   check (Date = cast(cast(cast(date as float) as int) as datetime)),Workday bit not null,Year as datepart(year, date),Month as datepart(month, date),Day as datepart(day, date),WeekDay as datepart(weekday, date))goinsert into dbo.Calendar (Date, Workday)select dateadd(day, number, '1/1/2000'),case  when datepart(weekday, dateadd(day, number, '1/1/2000')) between 2 and 6 then 1  else 0endfrom dbo.numbers -- A table of 10-thousand numbersgocreate index IDX_Calendar_MonthDay on dbo.Calendar(month, day)goupdate dbo.Calendarset workday = 0where month = 7 and day = 4or ... -- fill in other holidays heregoselect count(*)from dbo.Calendar where workday = 1and date between '5/20/2008' and '6/9/2008'[/code]With a table like that, you can easily have SQL do things like calculate the 1st Monday in September, or the 4th Thursday in November, record these things as holidays, and calculate workdays between dates.[code];with Thanksgiving (Row, Date, Workday) as  (select row_number() over (order by date), date, workday  from dbo.Calendar  where Month = 11  and WeekDay = 5)update Thanksgivingset workday = 0where row = 4[/code]You can also add more indexes to it, if you so desire.Using a 10-thousand day calendar starting from 1 Jan 2000, will give you a table that goes into 2027, which should be enough to start with.  As needed, add more, or create a job that runs on the first day of each year and adds another year worth of days (if you do that, make sure it adds enough to account for leap years).[/quote]Using the code above I came up with the code below for adding company holidays:How do I do it without using a cursor?--http://www.sqlservercentral.com/Forums/Topic513315-149-1.aspx#bm513318IF OBJECT_ID('Calendar', 'U') IS NOT NULL    DROP TABLE Calendarcreate table Calendar (Date datetime primary key,constraint CK_Date_NoTime   check (Date = cast(cast(cast(date as float) as int) as datetime)),Workday bit not null,Year as datepart(year, date),Month as datepart(month, date),Day as datepart(day, date),WeekDay as datepart(weekday, date),LongDay as datename(weekday, date),DayType varchar(50))go--create table Numbers (--Num_ID int)DECLARE @Numbers TABLE(Num_ID INT )declare @number as intset @number =1while @number &amp;lt;10001begininsert into @Numbers (num_id) values (@number)set @number=@number+1endinsert into dbo.Calendar (Date, Workday,DayType)select dateadd(day, num_id, '12/31/1999'),case  when datepart(weekday, dateadd(day, num_id, '12/31/1999')) between 2 and 6 then 1  else 0end,case  when datepart(weekday, dateadd(day, num_id, '12/31/1999')) between 2 and 6 then 'Work'  else 'Weekend'endfrom @Numbers -- A table of 10-thousand numbersgocreate index IDX_Calendar_MonthDay on dbo.Calendar(month, day)goupdate dbo.Calendarset workday = 0, DayType='New Years Day'where month = 1 and day = 1 goupdate dbo.Calendarset workday = 0, DayType='Independance Day'where month = 7 and day = 4 goupdate dbo.Calendarset workday = 0, DayType='Christmas Day'where month = 12 and day = 25 goDECLARE @CalendarYear TABLE([Year] INT )DECLARE @year intINSERT INTO @CalendarYear select distinct year from calendar order by yearDECLARE cYear CURSORFOR SELECT year FROM @CalendarYearOPEN cYearfetch cYear into @yearwhile @@fetch_status=0beginupdate dbo.Calendar set workday = 0, DayType='Memorial Day' where date=(select max(date) from calendar where month =5  and  year=@year and weekday=2)update dbo.Calendar set workday = 0, DayType='Labor Day' where date=(select  min(date) from calendar where month =9 and  year=@year and weekday=2)update dbo.Calendar set workday = 0, DayType='Thanksgiving Day'  where date=(select  max(date)-1 from calendar where month =11 and  year=@year and weekday=6)update dbo.Calendar set workday = 0, DayType='Day after Thanksgiving Day'  where date=(select  max(date) from calendar where month =11 and  year=@year and weekday=6)fetch cYear into @yearendclose cYear/*1st Jan						New Year's DayLast Monday in May			Memorial Day4th Jul						Independence DayFirst Monday in September	Labor DayFourth Thursday in November	Thanksgiving Day25th Dec					Christmas Day*/</description><pubDate>Wed, 18 Jun 2008 23:47:42 GMT</pubDate><dc:creator>Stephen Yale</dc:creator></item><item><title>RE: Find number of weekdays(Monday,Tuesday..) between two dates monthwise</title><link>http://www.sqlservercentral.com/Forums/Topic513315-149-1.aspx</link><description>For accurate counts of weekdays, I HIGHLY recommend a calendar table.  That way, you can include holidays, etc.[code]create table Calendar (Date datetime primary key,constraint CK_Date_NoTime   check (Date = cast(cast(cast(date as float) as int) as datetime)),Workday bit not null,Year as datepart(year, date),Month as datepart(month, date),Day as datepart(day, date),WeekDay as datepart(weekday, date))goinsert into dbo.Calendar (Date, Workday)select dateadd(day, number, '1/1/2000'),case  when datepart(weekday, dateadd(day, number, '1/1/2000')) between 2 and 6 then 1  else 0endfrom dbo.numbers -- A table of 10-thousand numbersgocreate index IDX_Calendar_MonthDay on dbo.Calendar(month, day)goupdate dbo.Calendarset workday = 0where month = 7 and day = 4or ... -- fill in other holidays heregoselect count(*)from dbo.Calendar where workday = 1and date between '5/20/2008' and '6/9/2008'[/code]With a table like that, you can easily have SQL do things like calculate the 1st Monday in September, or the 4th Thursday in November, record these things as holidays, and calculate workdays between dates.[code];with Thanksgiving (Row, Date, Workday) as  (select row_number() over (order by date), date, workday  from dbo.Calendar  where Month = 11  and WeekDay = 5)update Thanksgivingset workday = 0where row = 4[/code]You can also add more indexes to it, if you so desire.Using a 10-thousand day calendar starting from 1 Jan 2000, will give you a table that goes into 2027, which should be enough to start with.  As needed, add more, or create a job that runs on the first day of each year and adds another year worth of days (if you do that, make sure it adds enough to account for leap years).</description><pubDate>Mon, 09 Jun 2008 08:20:02 GMT</pubDate><dc:creator>GSquared</dc:creator></item><item><title>RE: Find number of weekdays(Monday,Tuesday..) between two dates monthwise</title><link>http://www.sqlservercentral.com/Forums/Topic513315-149-1.aspx</link><description>The formula in the following article will calculate weekdays without a loop.  There is, however, no consideration for holidays...[url]http://www.sqlservercentral.com/articles/Advanced+Querying/calculatingworkdays/1660/[/url]</description><pubDate>Sat, 07 Jun 2008 12:21:44 GMT</pubDate><dc:creator>Jeff Moden</dc:creator></item><item><title>RE: Find number of weekdays(Monday,Tuesday..) between two dates monthwise</title><link>http://www.sqlservercentral.com/Forums/Topic513315-149-1.aspx</link><description>--Create this function and call it from your query passing it --dbo.udf_NumXWeekDaysinMonth(CreationDate)CREATE Function dbo.udf_NumXWeekDaysinMonth(@Date datetime)RETURNS smallintASBEGINDeclare @dte varchar(10)Declare @TestDate varchar(10)Declare @i smallintDeclare @iNumDays smallintSet @dte = Convert(varchar(10),@Date,101)Set @i = 1Set @iNumDays = 0While @i &amp;lt; 32BeginSet @TestDate = cast(month(@dte) as varchar(2)) + '/' + cast(@i as varchar(2)) + '/' + Cast(Year(@dte) as varchar(4))--print @TestDateIF isdate(@TestDate) = 1  BEGIN    IF (DATENAME(dw, @TestDate) = DATENAME(dw, @dte))      BEGIN       Set @iNumDays = @iNumDays + 1      END  ENDSet @i = @i+1EndReturn @iNumDaysEND</description><pubDate>Sat, 07 Jun 2008 08:02:29 GMT</pubDate><dc:creator>KenSimmons</dc:creator></item><item><title>RE: Find number of weekdays(Monday,Tuesday..) between two dates monthwise</title><link>http://www.sqlservercentral.com/Forums/Topic513315-149-1.aspx</link><description>Database  - &amp;gt; LogBaseDatabase Columns - &amp;gt; CreationDate, TextMy Query to to calculate the actual count of queries fired on each Monday,Tuesday... for the above time range on a monthly basis.SELECT DATENAME(month, CreationDate) as DayName,DATENAME(dw, CreationDate) as DayName ,count(*) as ActualCount	FROM  LogBase	Where CreationDate between @fromDate and @toDate and DATENAME(dw, CreationDate)              group by DATENAME(dw, CreationDate)So here I am able to get number of queries/transaction done on each Monday,Tuesday,.. monthwise.What I am stuck at is how to I calculate the actual no. of Mondays, Tuesdays .. [b]per month [/b]for the given time range. (say range is from 3-june-2008 to 7-July-2008. So here no. of mondays in June would be 4 and no. of Mondays in July would be 1). I need this data so that I can calculate Average WeeKday Transactions on a monthly bias</description><pubDate>Sat, 07 Jun 2008 04:32:56 GMT</pubDate><dc:creator>nikhil_ambaye</dc:creator></item><item><title>RE: Find number of weekdays(Monday,Tuesday..) between two dates monthwise</title><link>http://www.sqlservercentral.com/Forums/Topic513315-149-1.aspx</link><description>Can you post what you have?  You may have to create a function depending on the query.</description><pubDate>Sat, 07 Jun 2008 02:17:01 GMT</pubDate><dc:creator>KenSimmons</dc:creator></item><item><title>Find number of weekdays(Monday,Tuesday..) between two dates monthwise</title><link>http://www.sqlservercentral.com/Forums/Topic513315-149-1.aspx</link><description>Hi All,I need to find average week day count on a monthly basis. My table has the creation date as a field which logs when a query was fired.Eg. start date - 1/15/2008; end date - 2/12/2009I am able to calculate the actual count of queries fired on each Monday,Tuesday... for the above time range on a monthly basis.I am stuck at a point where I need to find the actual no. of Mondays, Tuesdays .. per month for the given time range.Any help is welcome.TIA,Nikhil</description><pubDate>Sat, 07 Jun 2008 01:58:11 GMT</pubDate><dc:creator>nikhil_ambaye</dc:creator></item></channel></rss>