Oracle SQL Query用于获取给定月份的非工作时间

时间:2016-02-19 22:31:16

标签: sql oracle date

需要您的帮助来构建Oracle SQL查询,以捕获给定月份的非工作时间以获取行程列表。

传递的值将是开始日期和结束日期

例如:

Feb has totally 696 hrs
     Start Date        End Date 
S2 - 02-Feb-16 14:00 - 06-Feb-16 20:00 - 102hrs
S1 - 01-Feb-16 04:00 - 02-Feb-16 10:00 - 30hrs

                    Total Worked hrs   - 132 hrs

The query result expected is 564 hrs

尝试查询:

SELECT (a)
FROM   (
  SELECT COUNT( (SELECT DISTINCT 'O'
                 FROM   TRIP s,
                        TRUCK p
                 WHERE  s.TRUCKID = p.TRUCKID
                 AND    p.NOTES2='ABC'
                 AND    p.TRUCKID='553'
                 AND    ( to_date(d,'DD-Mon-YYYY HH24')
                          NOT BETWEEN to_date(s.STIME,'DD-Mon-YYYY HH24')
                          AND to_date(s.ETIME,'DD-Mon-YYYY HH24')
                        )
               ) ) a
  FROM  (
    SELECT (TRUNC(to_date(sysdate,'DD-MON-YYYY'),'MM') + level - 1) d
    FROM   dual
    CONNECT BY level <= TO_CHAR(LAST_DAY(to_date(sysdate,'DD-MON-YYYY')),'DD')
  )
)

1 个答案:

答案 0 :(得分:1)

WITH Trip_Dates ( Start_Date, End_Date ) AS (
  SELECT TO_DATE( '2016-02-02 14:00:00', 'YYYY-MM-DD HH24:MI:SS' ), TO_DATE( '2016-02-06 20:00:00', 'YYYY-MM-DD HH24:MI:SS' ) FROM DUAL UNION ALL
  SELECT TO_DATE( '2016-02-01 04:00:00', 'YYYY-MM-DD HH24:MI:SS' ), TO_DATE( '2016-02-02 10:00:00', 'YYYY-MM-DD HH24:MI:SS' ) FROM DUAL
)
SELECT ( ADD_MONTHS( TRUNC( SYSDATE, 'MM' ), 1 ) - TRUNC( SYSDATE, 'MM' )
         - SUM( End_Date - Start_Date ) ) * 24 AS Unworked_Hours
FROM   Trip_Dates;

<强>输出

UNWORKED_HOURS
--------------
           564