我正在SQL上开发一个自定义列。我们想看看平均日期差异,但我们需要排除周末。在我看来,从7到13之间的任何值中减去2,从14到20中减去4等都是最好的方法。
有办法做到这一点吗?
我以为这会是一个查询,但它不起作用。
当检查时间在7到13之间时。。。。。不知道如何减去这两个,但我想它会在那之后。
有什么想法吗??
您的方法将产生不正确的结果。星期五到星期一的日期差是3。既然这还不到7,你就不会错过周末。
如果要计算两个日期之间的工作日数,则需要确定哪些日子是工作日。以下脚本将计算两个日期之间的工作日数。
declare @StartDateRange date
declare @EndDateRange date
set @StartDateRange = {d '2019-09-01'}
set @EndDateRange = {d '2019-12-31'}
declare @StartDate date
declare @EndDate date
set @StartDate = {d '2019-12-20'}
set @EndDate = {d '2019-12-23'}
--set @StartDate = {d '2019-12-23'}
--set @EndDate = {d '2019-12-25'}
;
with days (i
, s
, dt) as
(
select 1
, @StartDateRange
, @StartDateRange
union all
select i + 1
, d.s
, dateadd(day, 1, dt)
from days d
where dateadd(day, 1, dt) < @EndDateRange
),
[Date] as (
SELECT dt as FullDate
, case when datepart(weekday, dt) in (1, 7) then 'Weekend'
else 'Weekday'
end as WeekdayWeekend
FROM days
)
select @StartDate as StartDate
, datename(weekday, @StartDate) as StartDayName
, @EndDate as EndDate
, datename(weekday, @EndDate) as EndDayName
, datediff(day, @StartDate, @EndDate) as DateDiff
, datediff(day, @StartDate, @EndDate) + 1 as DaysBetweenInclusive
, ( select count(*) as weekenddays
from [Date]
where FullDate between @StartDate and @EndDate
and WeekdayWeekend = 'Weekend') as WeekendDays
, ( select count(*) as weekenddays
from [Date]
where FullDate between @StartDate and @EndDate
and WeekdayWeekend = 'Weekday') as WeekDays
option (maxrecursion 0)
计数包括请求范围的开始和结束。例如,它将返回:
开始日期 | 结束日期 | 结束日期名称日期差异 | >包含 | >工作日工作日||||
---|---|---|---|---|---|---|---|
2019-12-20 | 周五 | 2019-11-23 | 周一3 | >4 | <2>2|||
2019-12-23 | 周一 | 2019-12-25 | 周三2 | 3 | 03|||
2019-12-21 | 周六 | 2019-12-28 | 周六7 | 8 | 3 | 5 |