除了当前季度到目前为止已经经过了多少个工作日之外,最好的方法是什么来拉动当前季度的工作日(星期一至星期五)?这是用于T-SQL / MS SQL
我目前有总天数,只需要删除周末...
datediff(dd, dateadd(qq, datediff(qq,0, getdate()),0), dateadd(qq, datediff(qq,0, getdate()) + 1 ,0)) as [Days in Quarter]
答案 0 :(得分:0)
执行此操作的方法如下:
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
;