我需要计算日期差异的平均值,不包括列中各行的周末。该查询给了我错误的结果。但是,当我自己计算时,我会得到不同的结果。查询类似于 -
select zone, avg(datediff(dd,startdate,enddate)-datediff((ww,startdate,enddate)*2)) from table where startdate >'1/1/2013' group by zone
我没有得到正确的结果。请指导我。
答案 0 :(得分:0)
试试这段代码:
select zone , avg(NumOfDays) from
(select zone, (datediff(dd,startdate,enddate)-datediff((ww,startdate,enddate)*2)) as NumOfDays from table where startdate >'1/1/2013')
group by zone
答案 1 :(得分:0)
我不知道你的数据是什么样的,你究竟挑战的是什么,但我认为你的问题是“排除周末”?也许这对你有帮助吗?
首先创建一个函数,计算您的句点之间的每个周末日,以便稍后过滤它:
CREATE FUNCTION fnc_GetWeekendDays(@dFrom DATETIME, @dTo DATETIME)
RETURNS INT AS
BEGIN
Declare @weekendDays int
Set @weekendDays = 0
While @dFrom <= @dTo
Begin
If ((datepart(dw, @dFrom) = 1) OR (datepart(dw, @dFrom) = 7))
Set @weekendDays = @weekendDays + 1
Set @dFrom = DateAdd(d, 1, @dFrom)
End
Return (@weekendDays)
END
在此之后,写下您的查询:
Select
zone,
avg(cast((datediff(SECOND,StartTime,EndTime) - dbo.fnc_GetWeekendDays(StartTime, EndTime)*86400) as float))
from
(
Select zone,
CASE
WHEN (datepart(dw, startdate) = 1) THEN DATEADD(Day, DATEDIFF(Day, 0, startdate), 1)
WHEN (datepart(dw, startdate) = 7) THEN DATEADD(Day, DATEDIFF(Day, 0, startdate), 2)
ELSE startdate END as StartTime,
CASE
WHEN (datepart(dw, enddate) = 1) THEN DATEADD(Day, DATEDIFF(Day, 0, enddate), -2)
WHEN (datepart(dw, enddate) = 7) THEN DATEADD(Day, DATEDIFF(Day, 0, enddate), -1)
ELSE enddateEND as EndTime
from table
) subquery
where StartTime < EndTime and startdate >'2013-01-01 00:00:00.000'
Group by zone
如果你想要另一种格式,你将得到平均时间(以秒为单位)......