计算两个不相邻行之间的差异

时间:2017-11-17 11:36:22

标签: sql oracle

如何根据表格中另一个字段中的值计算表格中两行之间的时差。 表(简化)看起来像;

Unit  Date              Status
0001  17.11.2017 09:52  INSPECTED
0001  17.11.2017 09:48  CLEAN
0001  17.11.2017 09:45  CLEANING
0001  17.11.2017 09:43  DIRTY
0001  16.11.2017 14:55  INSPECTED
0001  16.11.2017 14:54  CLEAN
0001  16.11.2017 12:54  CLEANING
0001  16.11.2017 12:22  DIRTY
0001  16.11.2017 12:20  CLEAN
0001  15.11.2017 10:48  CLEAN
0001  15.11.2017 10:27  CLEANING
0001  15.11.2017 09:03  DIRTY

日期字段的类型为DATE,单位和状态值来自父表。

根据列状态,我必须计算每天和每个单位的状态DIRTY和下一个状态CLEAN之间的差异。应该生成示例数据;

0001  17.11.2017  00:05
0001  16.11.2017  02:32
0001  15.11.2017  01:45

查询是Oracle APEX中图表的来源。

2 个答案:

答案 0 :(得分:0)

试试这个。

  SELECT a.unit,
         TRUNC (a.Date_t),
            TO_CHAR (
               EXTRACT (HOUR FROM NUMTODSINTERVAL (a.Date_t - b.Date_t, 'DAY')),
               'FM00')
         || ':'
         || TO_CHAR (
               EXTRACT (
                  MINUTE FROM NUMTODSINTERVAL (a.Date_t - b.Date_t, 'DAY')),
               'FM00')
            diff
    FROM (SELECT *
            FROM yourtable
           WHERE status = 'CLEAN') a
         JOIN (SELECT *
                 FROM yourtable
                WHERE status = 'DIRTY') b
            ON a.unit = b.unit AND TRUNC (a.Date_t) = TRUNC (b.Date_t)
ORDER BY 2 DESC;

答案 1 :(得分:0)

您不需要自联接 - 您可以使用LEAD分析函数:

SELECT unit,
       "Date",
       NUMTODSINTERVAL( Clean_date - "Date" =, 'DAY' ) AS difference
FROM   (
  SELECT t.*,
         LEAD( CASE status WHEN 'CLEAN' THEN "Date" END )
           IGNORE NULLS
           OVER ( PARTITION BY unit --, TRUNC( "Date" )
                  ORDER BY "Date" ASC ) AS Clean_date
  FROM   your_table t
)
WHERE status = 'DIRTY';