SQL查询,用于检索时间戳记值之间的时间间隔

时间:2018-08-23 18:20:15

标签: sql oracle timestamp date-difference

我在oracle中有两个表,我需要针对以下问题编写SQL查询

注意:客户端的工作时间为上午9 a.m.6 p.m

tab1包含问题创建和解决的时间戳记,

在选项卡1中,24th dec 20176:00 p.m(办公室关闭时间)出现问题,26th dec 201710 a.m.(办公室开门仅一个小时后)就得到解决)

我想计算创建和解决问题之间的时间,在这种情况下,这两个时间之间的时间为"one hour",因为25-dec-2017是假期

(节假日表中有节假日列表)

条件1::如果在两个日期之间存在假日,则应忽略

条件2::如果两个日期(创建和解决)之间都存在周末(星期六和星期日),则应将其忽略。

有人可以帮我吗?

tab1和tab2

tab1

tab2

1 个答案:

答案 0 :(得分:1)

您可以使用相关子查询来查找假期数(假期表中必须包括周末),并使用TIMESTAMP操作来获得结果。这适用于PostgreSQL,但应易于适用于Oracle:

SELECT issue_created_date, issue_resolved_date, ((days_in_bet - downtime_days) * INTERVAL '24 HOUR') + hours AS total_hours
FROM
(
SELECT issue_created_date, eod_timestamp, issue_resolved_date, sod_timestamp, downtime_days, 
       CASE WHEN DATE_TRUNC('DAY', issue_created_date) <> DATE_TRUNC('DAY', issue_resolved_date) THEN DATE(sod_timestamp) - DATE(eod_timestamp) - 1 ELSE 0 END AS days_in_bet,
       CASE WHEN DATE_TRUNC('DAY', issue_created_date) = DATE_TRUNC('DAY', issue_resolved_date) THEN issue_resolved_date - issue_created_date
        ELSE (eod_timestamp - issue_created_date) + (issue_resolved_date - sod_timestamp) END AS hours
FROM
(
    SELECT issue_created_date, DATE_TRUNC('DAY',issue_created_date) + INTERVAL '18 HOUR' AS eod_timestamp,
                                                                                    issue_resolved_date, DATE_TRUNC('DAY',issue_resolved_date) + INTERVAL '9 HOUR' AS sod_timestamp,
                                                                                    (SELECT COUNT(1) FROM tab2 h WHERE h.holiday BETWEEN i.issue_created_date AND i.issue_resolved_date) AS downtime_days
    FROM tab1 i 
) a1
) a2

请注意,此查询所做的一个重要假设是,只能在工作日内创建和解决问题。

输出:

issue_created_date    |  issue_resolved_date  | response_time_hours
"2017-12-24 18:00:00"   "2017-12-26 10:00:00"   "01:00:00"
"2017-12-26 13:00:00"   "2017-12-26 18:00:00"   "05:00:00"
"2017-12-27 08:00:00"   "2017-12-27 10:00:00"   "02:00:00"
"2017-12-27 14:00:00"   "2017-12-28 09:30:00"   "04:30:00"