包括假日在工作日计算

时间:2017-11-10 03:53:43

标签: sql sql-server sql-server-2012

CREATE TABLE [dbo].[Timedate](
    [TimeKey] [date] NULL,
    [DayName] [varchar](100) NULL,
    [Holiday] [varchar](10) NULL,
    [BusinessDays] [int] NULL,
    [QuarterNumber] [int] NULL,
    [CalenderWeek] [int] NULL,
    [MonthNo] [int] NULL,
    [CalenderMonth] [varchar](100) NULL,
    [CalenderMonthAbbrevation] [varchar](100) NULL,
    [CalenderMonthWeekNumber] [int] NULL,
    [CalenderDayabbrevation] [varchar](100) NULL
) ON [PRIMARY]

GO


 insert into timedate values ('2017-09-25','Monday','',1,3,'',9,'September','SEP',4,'MON')
 GO
 insert into timedate values ('2017-09-26','Tuesday','',1,3,'',9,'September','SEP',4,'Tue')
 GO
 insert into timedate values ('2017-09-27','Wednesday','',1,3,'',9,'September','SEP',4,'Wed')
 GO
 insert into timedate values ('2017-09-28','Thursday','',1,3,'',9,'September','SEP',4,'Thu')
 GO
 insert into timedate values ('2017-09-29','Friday','',1,3,'',9,'September','SEP',4,'Fri')
 GO
insert into timedate values ('2017-09-30','saturday','',0,4,'',10,'October','OCT',1,'Sat')
 GO
insert into timedate values ('2017-10-1','Sunday','',0,4,'',10,'October','OCT',1,'SUn')
 GO

我希望得到一个结果,比如Businessdays = 0然后previousworkingday = 1 当一个月中的2个工作日= 0然后上一个工作日= 2

注意: 1.Businessdays = 0定义假期 2.businessdays = 1定义了工作日。

2 个答案:

答案 0 :(得分:1)

查看您的示例数据和所需的输出,一种方法是使用ANSI标准OLAP函数来检查是否关注BusinessDays = 0BusinessDays {{1}然后not in sat/sun如下。

current BusinessDays +1

SELECT t.TimeKey, t.DayName, t.BusinessDays, CASE WHEN min(BusinessDays) over( ORDER BY TimeKey ROWS BETWEEN 1 following AND 1 following) = 0 AND BusinessDays <> 0 AND DayName NOT IN ('saturday', 'sunday') THEN BusinessDays + 1 ELSE BusinessDays END AS CalcValue FROM timedate t;

LEAD()

<强>结果:

SELECT t.TimeKey,
       t.DayName,
       t.BusinessDays,
       CASE
           WHEN lead(BusinessDays) over(
                                       ORDER BY TimeKey ) = 0
                AND BusinessDays <> 0
                AND DayName NOT IN ('saturday',
                                    'sunday') THEN BusinessDays + 1
           ELSE BusinessDays
       END AS CalcValue
FROM timedate t; 

<强> DEMO

答案 1 :(得分:0)

SELECT t.TimeKey,t.DayName,t.BusinessDays, case when(select count(1) from  timedate bd where bd.BusinessDays=0 and bd.TimeKey in (dateadd(day,2, t.timekey) ,  dateadd(day,1, t.timekey) )  and  [monthNo]=  datepart(mm,dateadd(day,2, t.timekey))and  [monthNo]=  datepart(mm,dateadd(day,1, t.timekey)))=2 then 3
when(select count(1) from  timedate bd where bd.BusinessDays=0 and (dateadd(day,1, t.timekey) =bd.TimeKey)and
 [monthNo]=  datepart(mm,dateadd(day,1, t.timekey)) and bd.BusinessDays<>t.BusinessDays )=1then 2  when t.BusinessDays=0 then 0else 1 end as valsFROM timedate t;