mysql查询查找引擎的持续时间

时间:2015-02-16 07:35:43

标签: mysql

我有像

这样的数据
  • 引擎 - 时间
  • on - 2015-02-16 10:00
  •         
  • on - 2015-02-16 10:30
  •         
  • on - 2015-02-16 10:40
  •         
  • off - 2015-02-16 10:50
  •         
  • off - 2015-02-16 11:00
  •         
  • off - 2015-02-16 11:10
  •         
  • on - 2015-02-16 11:20
  •         
  • on - 2015-02-16 11:30
  •         
  • on - 2015-02-16 11:40

我需要一个查询来查找当前状态,例如“引擎开启2015-02-16 11:20”

1 个答案:

答案 0 :(得分:0)

(根据评论,之前的尝试错误;再次尝试。)

SELECT @oo := engine FROM tbl ORDER BY time DESC LIMIT 1;  -- get 'on'
SELECT @prev := time FROM tbl
        WHERE engine != @oo
        ORDER BY time DESC  LIMIT 1;       -- 2015-02-16 11:10 (last 'off')
SELECT CONCAT(
          'engine ',
          UCASE(engine),
          ' from ',
          time )   AS 'current status'
    FROM tbl
    WHERE engine = @oo
      AND time > @prev
    ORDER BY time ASC
    LIMIT 1;