需要帮助来聚合/计算查询

时间:2013-06-21 13:47:01

标签: sql oracle

我有一张桌子:

214111  12-JUN-13 06:17:11  MOVING  PRIOD   143249  57  0   57  0
214111  12-JUN-13 06:17:35  MOVING  PRIOD   143249  55  0   55  0
214111  12-JUN-13 06:19:14  MOVING  SPEED   143249  71  0   71  0
214111  12-JUN-13 06:21:14  MOVING  PRIOD   143249  70  65  5   1
214111  12-JUN-13 06:23:14  MOVING  PRIOD   143249  70  0   70  0
214111  12-JUN-13 06:32:10  MOVING  PRIOD   143249  40  0   40  0
214111  12-JUN-13 06:55:35  MOVING  PRIOD   143249  63  55  8   1
214111  12-JUN-13 06:56:22  MOVING  PRIOD   143249  60  55  5   1
214111  12-JUN-13 07:02:43  MOVING  PRIOD   143307  27  0   27  0
214111  12-JUN-13 07:04:15  MOVING  PRIOD   143307  32  0   32  1
214111  12-JUN-13 07:04:25  MOVING  PRIOD   143307  22  0   22  1
214111  12-JUN-13 07:08:45  MOVING  PRIOD   143307  34  0   34  1

我想计算连续行中的1的数量。计数器将在重置时重置 0发生。

214111  12-JUN-13 06:17:11  MOVING  PRIOD   143249  57  0   57  0  0
214111  12-JUN-13 06:17:35  MOVING  PRIOD   143249  55  0   55  0  0
214111  12-JUN-13 06:19:14  MOVING  SPEED   143249  71  0   71  0  0
214111  12-JUN-13 06:21:14  MOVING  PRIOD   143249  70  65  5   1  1
214111  12-JUN-13 06:23:14  MOVING  PRIOD   143249  70  0   70  0  0
214111  12-JUN-13 06:32:10  MOVING  PRIOD   143249  40  0   40  0  0
214111  12-JUN-13 06:55:35  MOVING  PRIOD   143249  63  55  8   1  1
214111  12-JUN-13 06:56:22  MOVING  PRIOD   143249  60  55  5   1  2
214111  12-JUN-13 07:02:43  MOVING  PRIOD   143307  27  0   27  0  0
214111  12-JUN-13 07:04:15  MOVING  PRIOD   143307  32  0   32  1  1
214111  12-JUN-13 07:04:25  MOVING  PRIOD   143307  22  0   22  1  2
214111  12-JUN-13 07:08:45  MOVING  PRIOD   143307  34  0   34  1  3

需要帮助......

1 个答案:

答案 0 :(得分:2)

这有点棘手。使用lag()确定序列的起始位置 - 在0(或NULL)之后的1。然后执行这些值的累积和。累积和标识以1开始后跟0的序列。然后做一个累积和和一些逻辑来得到最终值:

select t.*,
       (case when val = 0 then 0
             else SUM(ind) over (partition by grp order by dt)
        end) as counter
from (select t.*, SUM(ind) over (order by dt) as grp
      from (select t.*,
                   (case when val = 1 and lag(val) over (order by dt) = 0 then 1 else 0
                    end) as ind
            from t
           ) t
     ) t