一种方法如下:
select
dates.*
, (DATEDIFF(dd, startofperiod, endofperiod) + 1)
-(DATEDIFF(wk, startofperiod, endofperiod) * 2)
-(CASE WHEN DATENAME(dw, startofperiod) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, endofperiod) = 'Saturday' THEN 1 ELSE 0 END)
as wkdaysinperiod
, (DATEDIFF(dd, startofperiod, today) + 1)
-(DATEDIFF(wk, startofperiod, today) * 2)
-(CASE WHEN DATENAME(dw, startofperiod) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, today) = 'Saturday' THEN 1 ELSE 0 END)
as wkdaystodate
from (
select
dateadd(qq, datediff(qq,0, getdate()),0) as startofperiod
, dateadd(dd,-1,dateadd(qq, datediff(qq,0, getdate()) + 1 ,0)) as endofperiod
, convert(date,getdate()) as today
) as Dates
;
上面看到的方法假设使用英语,所以如果不适合模数可以用来删除该依赖关系,如下所示。
SQL Server 中的“基准日期”是 1900-01-01,即星期一,因此自该日期除以 7、0 后的剩余天数为星期一、1、星期二、... 6 星期日。无论服务器 datefirst 设置如何,都是如此。
select
dates.*, ca.*
, (DATEDIFF(dd, startofperiod, endofperiod) + 1)
-(DATEDIFF(wk, startofperiod, endofperiod) * 2)
-(CASE WHEN periodstartdaynum = 6 THEN 1 ELSE 0 END) /* Sunday */
-(CASE WHEN periodenddaynum = 5 THEN 1 ELSE 0 END) /* Saturday */
as wkdaysinperiod
, (DATEDIFF(dd, startofperiod, today) + 1)
-(DATEDIFF(wk, startofperiod, today) * 2)
-(CASE WHEN periodstartdaynum = 6 THEN 1 ELSE 0 END) /* Sunday */
-(CASE WHEN todaydaynum = 5 THEN 1 ELSE 0 END) /* Saturday */
as wkdaystodate
from (
select
dateadd(qq, datediff(qq,0, getdate()),0) as startofperiod
, dateadd(dd,-1,dateadd(qq, datediff(qq,0, getdate()) + 1 ,0)) as endofperiod
, convert(date,getdate()) as today
) as Dates
cross apply (
select
datediff(dd,0,startofperiod) % 7 as periodstartdaynum
, datediff(dd,0,endofperiod) % 7 as periodenddaynum
, datediff(dd,0,today) % 7 as todaydaynum
) ca
;