我正在尝试将我的sql程序销售报告拉到一个月的当前工作日和时间。
至于今天:February Day: 9 Time gone: 45.0%
as:time gone = workingday_of_the_month / workingdays_of_(particular)month.
有没有人有想法,如何拉工作日和节假日除外?
答案 0 :(得分:0)
此功能允许您输入开始和结束日期,它将返回已用工作日数。我使用它的方法是添加一个英国公众假期的表格。然后,您可以将该函数用作SQL查询的一部分,以计算“时间消失”。
--Create table with each public holiday, including Y/N for Weekday.
CREATE TABLE [holidays](
[DayName] [varchar](20) NOT NULL,
[Date] [datetime] NOT NULL,
[Weekday] [varchar](1) NOT NULL
);
--2018 Bank Holidays
INSERT [holidays] ([DayName], [Date], [Weekday]) VALUES
(N'New Years Day','2018-Jan-01','Y'),
(N'Good Friday','2018-Mar-30','Y'),
(N'Easter Monday','2018-APr-02','Y'),
(N'Early May BH','2018-May-07','Y'),
(N'Spring BH','2018-May-28','Y'),
(N'Summer BH','2018-Aug-27','Y'),
(N'Christmas Day','2018-Dec-25','Y'),
(N'Boxing Day','2018-Dec-26','Y');
CREATE FUNCTION [WorkDayCount](
@Startdate datetime,
@EndDate datetime)
RETURNS INT
AS
BEGIN
DECLARE
@Holidays int,
@WorkDays int
SELECT @Holidays = COUNT(distinct Date) FROM HOLIDAYS
WHERE Date BETWEEN @StartDate AND @EndDate AND [Weekday]='Y'
SELECT @WorkDays = ((
-- Days between start and end dates
(DATEDIFF(dd, @StartDate, @EndDate))
-- Minus the number of weekend days between start and end dates
-(DATEDIFF(wk, @StartDate, @EndDate) * 2)
-- Minus an extra day if starting on a Sunday
-(CASE datepart(dw, @StartDate)+@@datefirst WHEN 8 THEN 1 ELSE 0 END)
-- Minus an extra day if ending on a saturday
-(CASE datepart(dw, @EndDate)+@@datefirst WHEN 7 THEN 1 WHEN 14 THEN 1 ELSE 0 END))
-- Minus Holiday Days
- @Holidays)
RETURN @WorkDays
END