-3

我有一张这样的桌子:

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

需要帮忙...

4

1 回答 1

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
于 2013-06-21T13:58:49.687 回答