0

data表:

/* TableName:Data */
  id  |  speed
----------------
   1  |   3
   2  |   0
   3  |   0
   4  |   5
   5  |   6
   6  |   7
   7  |   0
   8  |   0
   9  |   0
  10  |   3
   N  |   2

我想要一个结果(不重复零速),并指定移动状态;例子 :

如果第一行速度为零,Remove it from result否则显示,state=START/MOVE
如果移动状态后第一行速度为零,则设置state=STOP
如果速度在速度为零后以零值重复,Remove it from result
如果速度不为零,则设置state=START

示例结果:

      /* Results */
  id  |  speed  | status
-------------------------
   1  |   3     |  START/MOVE
   2  |   0     |  STOP
   4  |   5     |  START
   5  |   6     |  MOVE
   6  |   7     |  MOVE
   7  |   0     |  STOP
  10  |   3     |  START
   N  |   2     |  MOVE
4

1 回答 1

1
SELECT     a.*, 
           CASE WHEN @val IS NULL THEN @val:='START/MOVE'
                WHEN speed = 0 AND @val IN ('START/MOVE', 'START', 'MOVE') THEN @val:='STOP'
                WHEN speed > 0 AND @val = 'STOP' THEN @val:='START'
                WHEN speed > 0 AND @val IN ('START', 'MOVE') THEN @val:='MOVE'
           END AS status
FROM       (
           SELECT    a.*
           FROM      data a 
           LEFT JOIN (
                     SELECT MIN(id)-1 AS id, 0 AS speed
                     FROM   data 

                     UNION ALL

                     SELECT id, speed
                     FROM   data 
                     ) b ON a.id = b.id + 1 AND (a.speed,b.speed) IN ((0,0))
           WHERE     b.id IS NULL
           ) a
CROSS JOIN (SELECT @val:=NULL) val_init

测试和工作。

我会展示一个 SQLFiddle 演示,但不幸的是,他们的网站目前已关闭。

于 2012-08-02T11:16:24.650 回答