create a resultset of calendar dates - sql-server

I should use a stored procedure to fill a calendar for 10 years in a SQL database!
Three columns should I fill in with the records: date,weekday or weekend, dayname( monday,...).
Can somebody help me?

You can do it dynamically like this:
WITH Dates AS (
SELECT CONVERT(DATE, getdate()) as [Date]
UNION ALL
SELECT DATEADD(DAY, 1, [Date])
FROM Dates
where Date < dateadd(yy, 10, getdate())
)
SELECT [Date]
FROM Dates
OPTION (MAXRECURSION 4000)

try this version (floors the datetime and adds all requested columns):
;WITH Dates AS (
SELECT DATEADD(day,DATEDIFF(day,0,GETDATE()),0) as DateOf,
CASE WHEN datename(weekday,getdate()) IN ('Saturday','Sunday') THEN 'Weekend'
ELSE 'WeekDay'
END DayType,
datename(weekday,getdate()) DayOfWeekName
UNION ALL
SELECT DateOf+1,
CASE WHEN datename(weekday,DateOf+1) IN ('Saturday','Sunday') THEN 'Weekend'
ELSE 'WeekDay'
END DayType,
datename(weekday,DateOf+1) DayOfWeekName
FROM Dates
where DateOf < dateadd(yy, 10, getdate())
)
SELECT DateOf,DayType,DayOfWeekName
FROM Dates
OPTION (MAXRECURSION 4000)
to insert into a table try this:
DECLARE #DateTable table (DateOf datetime, DayType char(7), DayOfWeekName varchar(10))
;WITH Dates AS (
SELECT DATEADD(day,DATEDIFF(day,0,GETDATE()),0) as DateOf,
CASE WHEN datename(weekday,getdate()) IN ('Saturday','Sunday') THEN 'Weekend'
ELSE 'WeekDay'
END DayType,
datename(weekday,getdate()) DayOfWeekName
UNION ALL
SELECT DateOf+1,
CASE WHEN datename(weekday,DateOf+1) IN ('Saturday','Sunday') THEN 'Weekend'
ELSE 'WeekDay'
END DayType,
datename(weekday,DateOf+1) DayOfWeekName
FROM Dates
where DateOf < dateadd(yy, 10, getdate())
)
INSERT INTO #DateTable (DateOf,DayType,DayOfWeekName)
SELECT DateOf,DayType,DayOfWeekName
FROM Dates
OPTION (MAXRECURSION 4000)
select top 10 * from #DateTable
OTUPUT:
DateOf DayType DayOfWeekName
----------------------- ------- -------------
2011-05-16 00:00:00.000 WeekDay Monday
2011-05-17 00:00:00.000 WeekDay Tuesday
2011-05-18 00:00:00.000 WeekDay Wednesday
2011-05-19 00:00:00.000 WeekDay Thursday
2011-05-20 00:00:00.000 WeekDay Friday
2011-05-21 00:00:00.000 Weekend Saturday
2011-05-22 00:00:00.000 Weekend Sunday
2011-05-23 00:00:00.000 WeekDay Monday
2011-05-24 00:00:00.000 WeekDay Tuesday
2011-05-25 00:00:00.000 WeekDay Wednesday
(10 row(s) affected)

I apporached this as a tally table problem. I am using spt_values from Master as my tally table. It only goes up to 2048 which is enough data for 5.5 years. You can create your own tally table with as many numbers as you need.
Declare #startDate Date = '1/1/2011';
SELECT DateAdd(d, number, #startDate) [Date],
CASE WHEN DATEPART(dw, DateAdd(d, number, #startDate)) IN (1,7) THEN 'Weekend' ELSE 'Weekday' END [WeekDayEnd],
DateName(weekday, DateAdd(d, number, #startDate)) DayOfWeek
FROM spt_values
WHERE type = 'P';
This gets the following results:
Date WeekDayEnd DayOfWeek
2011-01-01 Weekend Saturday
2011-01-02 Weekend Sunday
2011-01-03 Weekday Monday
2011-01-04 Weekday Tuesday
2011-01-05 Weekday Wednesday
2011-01-06 Weekday Thursday
2011-01-07 Weekday Friday
2011-01-08 Weekend Saturday
2011-01-09 Weekend Sunday
2011-01-10 Weekday Monday

USE THIS
set nocount on
SET DATEFIRST 7;
go
select date,
datename(dw,datepart(dw,date)) Day,
datepart(dw,date) Day,
'Segment' = case
when datepart(dw,date)in (5,6) then 'WEEK_END' else 'Week_day' end
from calenderdate
set nocount off
> set nocount on
>
> select date,
> substring(cast(datename(dw,datepart(dw,date))as
> varchar(10)),1,3) Day, 'Segment' =
> case when datepart(dw,date)in (5,6)
> then 'WEEK_END' else 'Week_day' end
> from calenderdate
>
> set nocount off
output
1/1/2011 Monday 7 Week_day
1/2/2011 Tuesday 1 Week_day

Related

SQL Tally up value based on the day of the week

Here is what my table looks like
ID | Date
------------
13 2013-03-21 00:00:00
13 2013-03-23 00:00:00
13 2013-03-24 00:00:00
25 2013-03-21 00:00:00
25 2013-03-22 00:00:00
25 2013-03-21 00:00:00
25 2013-03-23 00:00:00
25 2013-03-28 00:00:00
25 2013-03-21 00:00:00
82 2013-03-22 00:00:00
82 2013-03-22 00:00:00
I want it to output (combine sat & sun into 'weekend'). It'll combine all the Mondays, Tuesdays, Wednesdays, etc. and combine the values.
day | total
--------------
Friday 2
Thursday 3
Weekend 3
This is my query so far
SELECT
CASE
WHEN DATENAME(weekday, [date]) = 'Saturday' OR DATENAME(weekday, [date]) = 'Sunday' THEN 'Weekend'
ELSE DATENAME(weekday, [date])
END AS Day,
COUNT(DISTINCT [id]) AS score
FROM [table]
GROUP BY
CASE
WHEN DATENAME(weekday, [date]) = 'Saturday' OR DATENAME(weekday, [date]) = 'Sunday' THEN 'Weekend'
ELSE DATENAME(weekday, [date])
END
Currently I can get my query to output this, but it seems like it isn't adding both thursdays or sat + sun.
Day | total
--------------
Friday 2
Thursday 2
Weekend 2
Appears like what you are actually after is a distinct count of the ID and date combined. Seems like the easiest way, therefore, would be to concatenate the 2 values to make a new unique value and COUNT those DISTINCT values:
SELECT CASE WHEN DATENAME(WEEKDAY, V.[Date]) IN ('Saturday','Sunday') THEN 'Weekend' ELSE DATENAME(WEEKDAY, V.[Date]) END AS [Weekday],
COUNT(DISTINCT CONCAT(ID,[date]))
FROM (VALUES (13, CONVERT(datetime2(0),'2013-03-21T00:00:00')),
(13, CONVERT(datetime2(0),'2013-03-23T00:00:00')),
(13, CONVERT(datetime2(0),'2013-03-24T00:00:00')),
(25, CONVERT(datetime2(0),'2013-03-21T00:00:00')),
(25, CONVERT(datetime2(0),'2013-03-22T00:00:00')),
(25, CONVERT(datetime2(0),'2013-03-21T00:00:00')),
(25, CONVERT(datetime2(0),'2013-03-23T00:00:00')),
(25, CONVERT(datetime2(0),'2013-03-28T00:00:00')),
(25, CONVERT(datetime2(0),'2013-03-21T00:00:00')),
(82, CONVERT(datetime2(0),'2013-03-22T00:00:00')),
(82, CONVERT(datetime2(0),'2013-03-22T00:00:00'))) V (ID, [Date])
GROUP BY CASE WHEN DATENAME(WEEKDAY, V.[Date]) IN ('Saturday','Sunday') THEN 'Weekend' ELSE DATENAME(WEEKDAY, V.[Date]) END;
Try this!
select count(id)as Total,Day from
(
select id, case when Datename(weekday,dt1) IN('Saturday','Sunday') then 'Weekend' else Datename(weekday,dt1) end as 'Day' from tab
)x
group by Day
Demo here
select Day,Count(day) cnt from (
SELECT
CASE
WHEN DATENAME(weekday, [date]) = 'Saturday' OR DATENAME(weekday, [date]) = 'Sunday' THEN 'Weekend'
ELSE DATENAME(weekday, [date])
END AS Day
,[date]
FROM [Infinite_campus].[dbo].[AttendanceRecord]
) as t
group by Day

SQL Server - assign day and night

I have following 2019 data.
Date Calendar_year Weekend_indicator
2019-01-01 2019 weekday
2019-01-01 2019 weekday
2019-01-02 2019 weekday
2019-01-02 2019 weekday
and so on.
I need to give one record a day and another a night value and have it repeated for the entire year's data so that it would look like this.
Date Calendar_year Weekend_indicator day_night
2019-01-01 2019 weekday Day
2019-01-01 2019 weekday Night
2019-01-02 2019 weekday Day
2019-01-02 2019 weekday Night
Here is my code.
DECLARE #Year AS INT,
#FirstDateOfYear DATETIME,
#LastDateOfYear DATETIME
-- You can change #year to any year you desire
SELECT #year = 2019
SELECT #FirstDateOfYear = DATEADD(yyyy, #Year - 1900, 0)
SELECT #LastDateOfYear = DATEADD(yyyy, #Year - 1900 + 1, 0)
-- Creating Query to Prepare Year Data;
WITH cte AS (
SELECT 1 AS DayID,
#FirstDateOfYear AS FromDate,
DATENAME(dw, #FirstDateOfYear) AS Dayname
UNION ALL
SELECT cte.DayID + 1 AS DayID,
DATEADD(d, 1 ,cte.FromDate),
DATENAME(dw, DATEADD(d, 1 ,cte.FromDate)) AS Dayname
FROM cte
WHERE DATEADD(d,1,cte.FromDate) < #LastDateOfYear
)
SELECT c.FromDate AS Date
,#Year as calendar_year
,CHOOSE(datepart(dw, c.FromDate), 'WEEKEND', 'WEEKDAY', 'WEEKDAY',
'WEEKDAY', 'WEEKDAY', 'WEEKDAY', 'WEEKEND') as weekend_indicator
FROM CTE c
CROSS JOIN ( values (1), (2) ) tb (FromDate)
WHERE DayName IN ('Saturday','Sunday')
or dayname not in ('Saturday', 'Sunday')
order by c.FromDate
OPTION (MaxRecursion 1000)
How do I assign the day and the night value and have it repeated?
This simple query might point you in the right direction:
USE TEMPDB
CREATE TABLE #T (DateCol DATE, Calender_Year INT)
INSERT INTO #T VALUES ('20180101', 2018 )
SELECT *
FROM #T
CROSS APPLY (VALUES ('Day'), ('Night') ) AS C (Val)
If you want just to change your code without rewriting it,
add one more row as below:
DECLARE #Year AS INT,
#FirstDateOfYear DATETIME,
#LastDateOfYear DATETIME
-- You can change #year to any year you desire
SELECT #year = 2019
SELECT #FirstDateOfYear = DATEADD(yyyy, #Year - 1900, 0)
SELECT #LastDateOfYear = DATEADD(yyyy, #Year - 1900 + 1, 0);
-- Creating Query to Prepare Year Data;
WITH cte AS (
SELECT 1 AS DayID,
#FirstDateOfYear AS FromDate,
DATENAME(dw, #FirstDateOfYear) AS Dayname
UNION ALL
SELECT cte.DayID + 1 AS DayID,
DATEADD(d, 1 ,cte.FromDate),
DATENAME(dw, DATEADD(d, 1 ,cte.FromDate)) AS Dayname
FROM cte
WHERE DATEADD(d,1,cte.FromDate) < #LastDateOfYear
)
SELECT c.FromDate AS Date
,#Year as calendar_year
,CHOOSE(datepart(dw, c.FromDate), 'WEEKEND', 'WEEKDAY', 'WEEKDAY',
'WEEKDAY', 'WEEKDAY', 'WEEKDAY', 'WEEKEND') as weekend_indicator,
case tb.FromDate when 1 then 'Day' else 'Night' end as day_night -----<<<<<<-----
FROM CTE c
CROSS JOIN ( values (1), (2) ) tb (FromDate)
WHERE DayName IN ('Saturday','Sunday')
or dayname not in ('Saturday', 'Sunday')
order by c.FromDate
OPTION (MaxRecursion 1000)
I use a table variable for create this solution.
DECLARE
#Year int
,#FirstDateOfYear date
,#LastDateOfYear date
,#date_loop date
SET #YEAR = 2019
SELECT
#FirstDateOfYear = DATEADD(yyyy, #Year - 1900, 0)
,#LastDateOfYear = DATEADD(yyyy, #Year - 1900 + 1, 0)
,#date_loop = DATEADD(yyyy, #Year - 1900, 0) --initialize variable for loop
DECLARE #date_table TABLE ([Date] date, [Calendar_year] int, [Weekend_indicator] varchar(10), [day_night] varchar(5))
WHILE #date_loop < #LastDateOfYear
BEGIN
INSERT #date_table
SELECT d.[Date], d.[Calendar_year], d.[Weekend_indicator], ca.[day_night]
FROM (
SELECT
#date_loop AS [Date]
,YEAR(#date_loop) AS [Calendar_year]
,CHOOSE(datepart(dw, #date_loop), 'weekend', 'weekday', 'weekday','weekday', 'weekday', 'weekday', 'weekend') AS [Weekend_indicator]) AS d
CROSS APPLY (
SELECT 'Day' AS [day_night]
UNION
SELECT 'Night'
) AS ca
SET #date_loop = DATEADD(day,1,#date_loop)
END
SELECT *
FROM #date_table
If you don't have a calendar or numbers table, you can use an ad-hoc table
Example
Declare #Date1 date = '2019-01-01'
Declare #Date2 date = '2019-12-31'
Select [Date] = d
,Calendar_year = datepart(YEAR,d)
,Weekend_indicator = case when datename(WEEKDAY,d) in ('Saturday','Sunday') then 'weekend' else 'weekday' end
,day_night
From (
Select Top (DateDiff(DAY,#Date1,#Date2)+1) D=DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),#Date1)
From master..spt_values n1,master..spt_values n2
) A
Cross Join (values ('Day'),('Night') ) b(day_night)
Order by D,day_night
Returns
Date Calendar_year Weekend_indicator day_night
2019-01-01 2019 weekday Day
2019-01-01 2019 weekday Night
2019-01-02 2019 weekday Day
2019-01-02 2019 weekday Night
...
2019-12-30 2019 weekday Day
2019-12-30 2019 weekday Night
2019-12-31 2019 weekday Day
2019-12-31 2019 weekday Night
Revised answer: I see an unused (VALUES ...) clause which could be used like so:
CROSS JOIN (VALUES ('Day'), ('Night') ) whatever(day_night)
DB Fiddle

How to calculate Saturday in between two dates in SQL Server

Week ends on Saturday and new week starts on Sunday.
I would like to determine date which will be a Saturday and split dates in SQL Server. Example below:
Start_date - 09/11/2018 - Friday
End_date - 12/11/2018 - Monday
Total number of days = 4
I would like split the days and end results as
Start_date - 09/11/2018 - Friday
Date1 - 10/11/2018 - Saturday
Total number of days = 2
Date2 - 11/11/2018 - Sunday
End_date - 12/11/2018 - Monday
Total number of days = 2
Another example ( start_date and end_date if there are more number of Saturdays e.g. )
start-date - 04/05/2017
end_date - 31/05/2017
Then results should be like below :-
Date1 Date2 no. of days.
------------------------------------
04/05/2017 06/05/2017 3
07/05/2017 13/05/2017 7
14/05/2017 20/05/2017 7
21/05/2017 27/05/2017 7
28/05/2017 31/05/2017 4
Please help.
Thanks & Regards,
VG
If I am not mistaken you are looking for something like this:
DECLARE #StartDate DATE = '2017-05-04'
DECLARE #EndDate DATE = '2017-05-31'
DECLARE #OutputTABLE AS TABLE
(
StartDate DATE NOT NULL,
EndDate DATE NOT NULL
)
DECLARE #NumberOfWeeks INT = DATEDIFF(week, #StartDate, #EndDate)
DECLARE #Counter INT = 0
DECLARE #TempDate DATE = DATEADD(week, #Counter, #StartDate)
WHILE #NumberOfWeeks >= 0
BEGIN
IF #NumberOfWeeks = 0
BEGIN
INSERT INTO #OutputTABLE VALUES (#TempDate, #EndDate);
END
ELSE
BEGIN
INSERT INTO #OutputTABLE VALUES (#TempDate, DATEADD(DAY, -1, DATEADD(week, DATEDIFF(week ,0 , #TempDate) + 1, -1)));
END
SET #TempDate = DATEADD(week, #Counter + 1, DATEADD(day, -1, DATEADD(week, DATEDIFF(week, 0, #StartDate), 0)))
SET #NumberOfWeeks = #NumberOfWeeks - 1
SET #Counter = #Counter + 1
END
SELECT StartDate,
EndDate,
DATEDIFF(day, StartDate, EndDate) + 1 AS NumberOfDays
FROM #OutputTABLE
Here is one way. I couldn't figure out a way with a recursive CTE since you can't aggregate in the recursive part of a recursive CTE.
DECLARE #MinDate DATE = '20170504',
#MaxDate DATE = '20170531'
DECLARE #StartDate datetime, #EndDate datetime
--DATE TABLE... ONE ROW FOR EVERY DAY IN RANGE
IF OBJECT_ID('tempdb..#DateTable') IS NOT NULL DROP TABLE #DateTable
SELECT TOP (DATEDIFF(DAY, #MinDate, #MaxDate) + 1)
Dates = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, #MinDate)
INTO #DateTable
FROM sys.all_objects a
CROSS JOIN sys.all_objects b
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (Date1 DATETIME, Date2 DATETIME, NumOfDays INT)
--INSERT FIRST ROW IN CASE IT STARTS ON A DAY OTHER THAN SUNDAY
INSERT INTO #Results
SELECT
MIN(Dates) as Date1
,MIN(CASE WHEN DATEPART(WEEKDAY,Dates) = 7 THEN Dates END) as Date2
,DATEDIFF(DAY,MIN(Dates),MIN(CASE WHEN DATEPART(WEEKDAY,Dates) = 7 THEN Dates END)) + 1 as NoOfDays
FROM #DateTable
SET #StartDate = (SELECT MIN(CASE WHEN DATEPART(WEEKDAY,Dates) = 1 THEN Dates END) FROM #DateTable)
SET #EndDate = (SELECT MAX(CASE WHEN DATEPART(WEEKDAY,Dates) = 1 THEN Dates END) FROM #DateTable)
--INSERT ALL FULL WEEKS
WHILE #StartDate < #EndDate
BEGIN
INSERT INTO #Results
SELECT
MIN(Dates) as Date1
,MIN(CASE WHEN DATEPART(WEEKDAY,Dates) = 7 THEN Dates END) as Date2
,DATEDIFF(DAY,MIN(Dates),MIN(CASE WHEN DATEPART(WEEKDAY,Dates) = 7 THEN Dates END)) + 1 as NoOfDays
FROM #DateTable
WHERE Dates >= #StartDate
SET #StartDate = DATEADD(DAY,7,#StartDate)
END
--INSERT LAST ROW IF IT ISN'T A FULL WEEK
IF (SELECT MAX(Date2) FROM #Results) <> #MaxDate
BEGIN
INSERT INTO #Results
SELECT
MIN(Dates) as Date1
,MAX(Dates) as Date2
,DATEDIFF(DAY,MIN(Dates),MAX(Dates)) + 1 as NoOfDays
FROM #DateTable
WHERE Dates > (SELECT MAX(Date2) FROM #Results)
END
SELECT * FROM #Results
DROP TABLE #Results
DROP TABLE #DateTable
RETURNS
+-------------------------+-------------------------+-----------+
| Date1 | Date2 | NumOfDays |
+-------------------------+-------------------------+-----------+
| 2017-05-04 00:00:00.000 | 2017-05-06 00:00:00.000 | 3 |
| 2017-05-07 00:00:00.000 | 2017-05-13 00:00:00.000 | 7 |
| 2017-05-14 00:00:00.000 | 2017-05-20 00:00:00.000 | 7 |
| 2017-05-21 00:00:00.000 | 2017-05-27 00:00:00.000 | 7 |
| 2017-05-28 00:00:00.000 | 2017-05-31 00:00:00.000 | 4 |
+-------------------------+-------------------------+-----------+
This will compute your Date2 from your Date1
print dateadd(day,-1,dateadd(wk,datepart(wk,'4/5/2017'),'1/1/2017'))

SQL Server - Get Last Business Data excluding holidays and Weekends

I use this query to get the last business date excluding weekends:
DECLARE #LastBizDate as DATETIME
SELECT #LastBizDate = (DATEADD(DAY, CASE DATENAME(WEEKDAY, GETDATE())
WHEN 'Saturday' THEN -1
WHEN 'Sunday' THEN -2
ELSE -1 END, DATEDIFF(DAY, 0, GETDATE())))
SELECT #LastBizDate AS 'Last_Business_Date'
But how can I exclude the holidays?
I have this tbl_Holidays table with sample data:
-------------------------
|Holiday_Date |
|-----------------------|
|2017-04-14 00:00:00.000|
|2017-05-01 00:00:00.000|
|2017-10-18 00:00:00.000|
|2017-12-25 00:00:00.000|
-------------------------
Note: no need to consider that when the holiday falls on Sunday, then Monday will be considered Off. Again, no need to consider that.
Thank you in advance.
I think you need a loop to do this.
After excluding saturday and sunday, you need to check whether the date is in the holiday table. Again you need to check the date (calculated after excluding from holiday table )falls on sunday and saturday.
DECLARE #last_wrk_day DATETIME
,#today DATETIME
DECLARE #TblHoliday AS TABLE (Holiday_Date DATE)
INSERT INTO #TblHoliday
VALUES ('2017-04-14 00:00:00.000')
,('2017-05-01 00:00:00.000')
,('2017-10-18 00:00:00.000')
,('2017-12-25 00:00:00.000')
,('2017-04-13 00:00:00.000')
SET #today = '2017-04-10 00:00:00.000' --getdate()
SET #last_wrk_day = dateadd(day, - 1, #today)
WHILE (
(
SELECT TOP 1 1
FROM #TblHoliday
WHERE Holiday_Date = #last_wrk_day
) = 1
OR DATEPART(dw, #last_wrk_day) IN (1, 7)
)
BEGIN
SET #last_wrk_day = dateadd(day, - 1, #last_wrk_day)
END
SELECT #last_wrk_day
OUTPUT
2017-04-13 00:00:00.000

Grouping date periods (by number of days) but exclude the weekends?

I have a table with start and end dates in. My goal is to have a table that has grouped these dates into how many days the period spans. I thought I had the solution with a simple SQL statement (MS SQL Server 2005) but I want to exclude weekends.
SELECT DATEDIFF(D, StartDate, EndDate)+1 AS Days,
COUNT(ID) as Count
FROM myDateTable
GROUP BY DATEDIFF(D, StartDate, EndDate)
This gives a record set of:
Days Count
1 4
2 2
4 1
7 2
Is this possible to exclude the weekends in the SQL statement and if not can it be done using ASP and a array perhaps?
Well then, using Sql Server 2005, you can try something like
DECLARE #Table TABLE(
ID INT,
StartDate DATETIME,
EndDate DATETIME
)
INSERT INTO #Table (ID,StartDate,EndDate) SELECT 1, '25 Jan 2009', '31 Jan 2009'
INSERT INTO #Table (ID,StartDate,EndDate) SELECT 2, '01 Jan 2009', '07 Jan 2009'
INSERT INTO #Table (ID,StartDate,EndDate) SELECT 3, '01 Jan 2009', '14 Jan 2009'
DECLARE #MinDate DATETIME,
#MaxDate DATETIME
SELECT #MinDate = MIN(StartDate) ,
#MaxDate = MAX(EndDate)
FROM #Table
--Create a temp result set between the Min and Max dates, with all dates, and their weekday names
;WITH DayValues AS(
SELECT #MinDate DateVal,
DATENAME(dw, #MinDate) DateValName
UNION ALL
SELECT DateVal + 1,
DATENAME(dw, DateVal + 1) DateValName
FROM DayValues
WHERE DateVal + 1 <= #MaxDate
),
--select the count of days for each StartDate and EndDate pair, excluding Saturdays and Sundays
DateCounts AS(
SELECT ID,
(
SELECT COUNT(1)
FROM DayValues
WHERE DateVal BETWEEN StartDate AND EndDate
AND DateValName NOT IN ('Saturday', 'Sunday')
) DateCount
FROM #Table
)
--Now group and count
SELECT DateCount,
COUNT(ID) TotalCount
FROM DateCounts
GROUP BY DateCount
OPTION (MAXRECURSION 0)
Output
DateCount TotalCount
----------- -----------
5 2
10 1
EDIT: Brief Explenation
You need to determine the number of days between (and including) 2 dates, that are not weekends.
So using a CTE, I create a temporary result set of dates ebwteen the Min and Max dates, and their Weekday Name (eg Monday, Tuesday... Sunday).
Then, for each of your date pairs, I count the number of entries that does not correspond to Saturday and Sunday.
Here's an ASP function that counts days weekdays between two dates.
<%
Dim StartDate, EndDate
StartDate = CDate("1/1/2010")
EndDate = CDate("2/1/2010")
Response.Write(WeekDayCount(StartDate, EndDate))
Function WeekDayCount(StartDate, EndDate)
dim tempDate, dayCount
tempDate = StartDate
dayCount = 0
'Step forward one day, counting non-week days
While tempDate <> EndDate
'The 1 and 7 might need to be tweaked depending on the locale of your
'server. 1 = Sunday, 7 = Saturday
If DatePart("w", tempDate) <> 1 And DatePart("w", tempDate) <> 7 Then
dayCount = dayCount + 1
End If
tempDate = DateAdd("d", 1, tempDate)
Wend
WeekDayCount = dayCount
End Function
%>
Have a look at ##DATEFIRST,
and look a this;
SELECT DATEPART(DW,GETDATE()).
You should be able to run a query WHERE the 'DW' is not equal to the weekend numbers.

Resources