我有一个包含开始日期和结束日期的表格。我的目标是有一个表格,将这些日期分组为期间跨越的天数。我以为我有一个简单的SQL语句(MS SQL Server 2005)的解决方案,但我想排除周末。
SELECT DATEDIFF(D, StartDate, EndDate)+1 AS Days,
COUNT(ID) as Count
FROM myDateTable
GROUP BY DATEDIFF(D, StartDate, EndDate)
这给出了一组记录:
Days Count
1 4
2 2
4 1
7 2
是否可以在SQL语句中排除周末,如果不能,可以使用ASP和数组来完成?
答案 0 :(得分:1)
那么,使用Sql Server 2005,你可以尝试像
这样的东西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)
输出
DateCount TotalCount
----------- -----------
5 2
10 1
编辑:简要消费
您需要确定两个日期(包括)之间的天数,而不是周末。
因此,使用CTE,我创建一个临时结果日期,包括最小和最大日期,以及他们的工作日名称(例如星期一,星期二......星期日)。
然后,对于每个日期对,我计算与周六和周日不对应的条目数。
答案 1 :(得分:0)
这是一个ASP函数,它计算两个日期之间的工作日。
<%
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
%>
答案 2 :(得分:0)
看看@@ DATEFIRST,
看一下这个;
SELECT DATEPART(DW,GETDATE())。
您应该能够运行查询,其中'DW'不等于周末数。