TSQL仅限工作时间

时间:2015-01-14 14:44:49

标签: sql-server tsql time datediff

在视图中,这两个日期来自一个表格:

2014-12-17 14:01:03.523 - 2014-12-20 09:59:28.783

我需要知道几小时内的日期差异,假设在一天中我可以计算上午8点和下午5点的小时数。

当然,周六和周日不得包括在内。

我尝试在select中使用此代码,但我只在几天内获得差异,不包括星期六和星期日。

(DATEDIFF(HOUR, convert(datetime,t.EXT_DATAINS-2), convert(datetime,b.EXT_DATAINS-2)) + 1) 
  -(DATEDIFF(wk, convert(datetime,t.EXT_DATAINS-2), convert(datetime,b.EXT_DATAINS-2)) * 2)
  -(CASE WHEN DATENAME(dw, convert(datetime,t.EXT_DATAINS-2)) = 'Sunday' THEN 1 ELSE 0 END)
  -(CASE WHEN DATENAME(dw, convert(datetime,b.EXT_DATAINS-2)) = 'Saturday' THEN 1 ELSE 0 END) differenza

示例:

2014-12-17 : 3hrs
2014-12-18 : 8hrs
2014-12-19 : 8hrs
2014-12-20 : 2hrs 
Tot        : 21hrs

2 个答案:

答案 0 :(得分:2)

使用Recursive CTE获取所有带日期的小时数。

方法1:获取FromDate和ToDate之间的所有日期

DECLARE @FROMDATE DATETIME='2014-12-17 14:01:03.523'
DECLARE @TODATE DATETIME='2014-12-20 09:59:28.783'

;WITH CTE AS
(
   SELECT @FROMDATE FROMDATE
   UNION ALL
   SELECT DATEADD(HH,1,FROMDATE)
   FROM CTE
   WHERE FROMDATE<@TODATE 
)
SELECT ISNULL(CAST(CAST(FROMDATE AS DATE)AS VARCHAR(12)),'Tot')FROMDATE,
CAST(COUNT(FROMDATE)AS VARCHAR(4))+'hrs' [HOURS] 
FROM CTE
WHERE DATEPART(HH,FROMDATE) BETWEEN 9 AND 16
AND DATENAME(DW,FROMDATE)<>'SATURDAY' AND DATENAME(DW,FROMDATE)<>'SUNDAY'
GROUP BY CAST(FROMDATE AS DATE)
WITH ROLLUP

方法2:获取FromDate和ToDate之间缺少的日期,其中8为硬编码为

此方法将更具可实施性 - 性能调整

DECLARE @FROMDATE DATETIME='2014-12-17 14:01:03.523'
DECLARE @TODATE DATETIME='2014-12-20 09:59:28.783'

;WITH CTE AS
(
   -- Get missing dates between FromDate and ToDate
   SELECT  DATEADD(DAY,1,@FROMDATE) FROMDATE,8 HRS
   UNION ALL
   SELECT DATEADD(DAY,1,FROMDATE),8
   FROM CTE
   WHERE FROMDATE < DATEADD(DAY,-1,@TODATE) 
)
,CTE2 AS
(
   -- Gets the Hours for FromDate
   SELECT CAST(@FROMDATE AS DATE) DATES, CAST(CAST(DATEDIFF
   (
      MINUTE,@FROMDATE,CAST(CAST(CAST(@FROMDATE AS DATE) AS VARCHAR(12))+' 17:00:00' AS DATETIME)
   )AS NUMERIC(18,2))/60 AS DECIMAL(18,0)) HRS
   WHERE DATENAME(DW,@FROMDATE)<>'SATURDAY' AND DATENAME(DW,@FROMDATE)<>'SUNDAY'

   UNION ALL

   -- Select Hours in between dates
   SELECT CAST(FROMDATE AS DATE) NEWDATE,HRS
   FROM CTE
   WHERE DATENAME(DW,FROMDATE)<>'SATURDAY' AND DATENAME(DW,FROMDATE)<>'SUNDAY'

   UNION ALL

   -- Select Hours for ToDate
   SELECT CAST(@TODATE AS DATE), CAST(CAST(DATEDIFF
   (
      MINUTE,CAST(CAST(CAST(@TODATE AS DATE) AS VARCHAR(12))+' 08:00:00' AS DATETIME),@TODATE
   )AS NUMERIC(18,2))/60 AS DECIMAL(18,0))
   WHERE DATENAME(DW,@TODATE)<>'SATURDAY' AND DATENAME(DW,@TODATE)<>'SUNDAY'
)
-- Use ROLLUP to find the sum of Hours and show it in last row
SELECT ISNULL(CAST(DATES AS VARCHAR(20)),'Tot')DATES,
CAST(SUM(HRS)AS VARCHAR(4))+'hrs' HRS
FROM CTE2
GROUP BY DATES
WITH ROLLUP

答案 1 :(得分:0)

@marco burrometo

创建一个静态表,它将具有假日功能,星期六和星期日等所有日历功能。它会对你有所帮助。