两个日期之间不同,不包括美国假期

时间:2014-09-03 10:42:23

标签: sql sql-server tsql

SELECT CONVERT(VARCHAR(12), (
            datediff(ss, RIM.Createddate, Getdate()) - (
                SELECT dbo.fn_GetHolidaysAndSaturdayAndSundayCount(RIM.Createddate, Getdate())
                ) * 24 * 60 * 60
            ) / 60 / 60 / 24) + ' Day(s) ' + ':' + CONVERT(VARCHAR(12), (
            datediff(ss, RIM.Createddate, Getdate()) - (
                SELECT dbo.fn_GetHolidaysAndSaturdayAndSundayCount(RIM.Createddate, Getdate())
                ) * 24 * 60 * 60
            ) / 60 / 60 % 24) + ' Hour(s) '
FROM requestinstancemt RIM

假设RIM.Createddate = '2014-08-31 23:00:00.000'。我想排除星期六,星期日和假日,我想把工作时间只返回工作日。

查询仅提供计数。我试图将计数更改为小时它不起作用。

1 个答案:

答案 0 :(得分:1)

单程......

CREATE TABLE #Days (ActualDay Date, DayOf varchar(10), Holiday bit)

INSERT #Days SELECT '9/1/2014', DATENAME(dw,'9/1/2014'), 1
INSERT #Days SELECT '9/2/2014', DATENAME(dw,'9/2/2014'), 0
INSERT #Days SELECT '9/3/2014', DATENAME(dw,'9/3/2014'), 0
INSERT #Days SELECT '9/4/2014', DATENAME(dw,'9/4/2014'), 0
INSERT #Days SELECT '9/5/2014', DATENAME(dw,'9/5/2014'), 0
INSERT #Days SELECT '9/6/2014', DATENAME(dw,'9/6/2014'), 0
INSERT #Days SELECT '9/7/2014', DATENAME(dw,'9/7/2014'), 0
INSERT #Days SELECT '9/8/2014', DATENAME(dw,'9/8/2014'), 0
INSERT #Days SELECT '9/9/2014', DATENAME(dw,'9/9/2014'), 0
INSERT #Days SELECT '9/10/2014', DATENAME(dw,'9/10/2014'), 0

SELECT COUNT(*) 
FROM #Days
WHERE ActualDay BETWEEN '9/1/2014' AND '9/9/2014'
    AND Holiday = 0
    AND DayOf NOT IN ('Saturday', 'Sunday')

另一个选项(某些代码来自Count work days between two dates)...

CREATE TABLE #Holidays (Holiday Date)


INSERT #Holidays SELECT '1/1/14'
INSERT #Holidays SELECT '1/20/14'
INSERT #Holidays SELECT '2/17/14'
INSERT #Holidays SELECT '4/18/14'
INSERT #Holidays SELECT '5/26/14'
INSERT #Holidays SELECT '7/4/14'
INSERT #Holidays SELECT '9/1/14'
INSERT #Holidays SELECT '10/13/14'
INSERT #Holidays SELECT '11/11/14'
INSERT #Holidays SELECT '11/27/14'
INSERT #Holidays SELECT '12/25/14'


DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
DECLARE @Holidays int
SET @StartDate = '1/1/14'
SET @EndDate = '1/3/14'

SELECT @Holidays = COUNT(*) FROM #Holidays WHERE Holiday BETWEEN @StartDate AND @EndDate

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) 
  - @Holidays