Oracle - 根据Value和Next行返回上一行

时间:2015-11-16 10:20:13

标签: sql oracle

我有一个小问题,我一直试图理清......

数据库显示特定Cell的不可用记录。如果Cell已启动,则将0记录为不可用,当该单元关闭时,显示为3600(秒)。当一个记录在其中一个字段中有3600时,则将1放在另一个字段中,以将其显示为Cell Out of of Service(COOS)。

我已经能够搜索记录以显示所有当前的COOS,但我需要做的是搜索并显示一个单元格何时关闭以及何时重新启动......

所以我需要在数据库中搜索'3600'的第一个实例然后带回显示'0'的前一个记录,然后再带回下一个显示'0'的记录,然后这将告诉我日期/细胞熄灭的时间。

这是数据的一个例子:

enter image description here

我需要查询带回来:

enter image description here

干杯, 麦克

1 个答案:

答案 0 :(得分:0)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE Data ( Cell, Date_Time, COOS, Unavailability ) AS
          SELECT 'D02463', DATE '2015-11-16' + INTERVAL '10' HOUR, 1, 0 FROM DUAL
UNION ALL SELECT 'D02463', DATE '2015-11-16' + INTERVAL '9' HOUR, 0, 3600 FROM DUAL
UNION ALL SELECT 'D02463', DATE '2015-11-16' + INTERVAL '8' HOUR, 0, 3600 FROM DUAL
UNION ALL SELECT 'D02463', DATE '2015-11-16' + INTERVAL '7' HOUR, 0, 3600 FROM DUAL
UNION ALL SELECT 'D02463', DATE '2015-11-16' + INTERVAL '6' HOUR, 0, 3600 FROM DUAL
UNION ALL SELECT 'D02463', DATE '2015-11-16' + INTERVAL '5' HOUR, 1, 0 FROM DUAL
UNION ALL SELECT 'D02463', DATE '2015-11-16' + INTERVAL '4' HOUR, 1, 0 FROM DUAL
UNION ALL SELECT 'D02463', DATE '2015-11-16' + INTERVAL '3' HOUR, 1, 0 FROM DUAL

查询1

SELECT Cell,
       Cell_Down,
       Cell_Up,
       (Cell_Up - Cell_Down)*24 AS Time_Down
FROM   (
  SELECT Cell,
         Date_Time AS Cell_Up,
         LAG( Date_Time ) OVER ( PARTITION BY Cell ORDER BY Date_Time ) + INTERVAL '1' HOUR AS Cell_Down
  FROM   Data
  WHERE  COOS = 1
)
WHERE Cell_Down < Cell_Up

<强> Results

|   CELL |                  CELL_DOWN |                    CELL_UP | TIME_DOWN |
|--------|----------------------------|----------------------------|-----------|
| D02463 | November, 16 2015 06:00:00 | November, 16 2015 10:00:00 |         4 |