我创建了一个查询,可以在两个日期之间进行搜索,以计算不包括银行假日的工作日。
我创建了一个日期在银行假期内的表格
如何创建一个查询,在两个日期之间进行搜索时,它会排除表格中的日期?
这是我到目前为止所拥有的......
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
-- Calculate the calendar working days below INCLUDING BH
--YEAR/MONTH/DATE
SET @StartDate = '2016/09/01'
SET @EndDate = '2016/09/30'
SELECT
(DATEDIFF(dd, @StartDate, @EndDate) + 1)
-(DATEDIFF(wk, @StartDate, @EndDate) * 2)
-(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
DECLARE @TotalDays INT, @WorkDays INT
SET @TotalDays = (DATEDIFF(dd, @StartDate, @EndDate) +1)
print @TotalDays
答案 0 :(得分:1)
您可以通过操作此
来计算两个日期DECLARE @sql VARCHAR(500),
@Region VARCHAR(100) = 'COLUMN2', --It can be Column1, Column2.....
@StartDate DATETIME = '2016-04-10',
@EndDate DATETIME = '2016-04-15'
SET @sql = '
SELECT
COUNT(' + @Region + ')
FROM bankholidays
WHERE ' + @Region + ' BETWEEN ''' + CAST(@StartDate AS VARCHAR) + ''' AND ''' + CAST(@EndDate AS VARCHAR) + ''''
EXEC (@SQL)
答案 1 :(得分:0)
您似乎已经使用this trick来获取两个日期之间的工作日(即不包括周末)。
注意:此解决方案假定会话的语言为英语,周六和周日被视为非工作日;这些假设可能不适用于所有文化。
来自this post,您似乎已经在排除银行假期的正确轨道上了。即
DECLARE @StartDate DATETIME = '2016-09-01'
DECLARE @EndDate DATETIME = '2016-09-30'
DECLARE @TotalDays INT, @WorkDays INT
SELECT
@TotalDays = (DATEDIFF(dd, @StartDate, @EndDate) +1)
, @WorkDays =
(DATEDIFF(dd, @StartDate, @EndDate) + 1) --get the number of working days between 2 dates (including the date itself)
-(DATEDIFF(wk, @StartDate, @EndDate) * 2) --get the number of weekend days (i.e. 2 x number of weeks)
-(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END) --\_then take into account if the current date fell over a weekend
-(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END) --/
- coalesce(
(
select count(1)
from BankHolidays
where HolidayDate between @StartDate and @EndDate
)
,0) --and remove any bank holidays which fall during this period
print @TotalDays
print @WorkDays
另请注意,这假设您表中的所有银行假日都是工作日;不是周末(即否则那些日子将被包括两次)。