如何从mysql查询以获得以下解决方案?

时间:2012-12-19 12:48:07

标签: mysql database

如何查询

SL  STATUS    DATETIME
1   STOP      2012-12-19 13:10:00    
2   STOP      2012-12-19 13:12:00       
3   STOP      2012-12-19 13:14:00   
4   STOP      2012-12-19 13:16:00   
5   STOP      2012-12-19 13:18:00    
6   STOP      2012-12-19 13:20:00
7   START     2012-12-19 13:22:00 

从表mysql查询

SL  STATUS    DATETIME                   STOPPAGE
1   STOP      2012-12-19 13:10:00        00:10
2   START     2012-12-19 13:22:00

我必须将日期值之间的差异理解为 STOPPAGE ,其状态为停止

3 个答案:

答案 0 :(得分:1)

SELECT * FROM <TABLENAME> WHERE ID IN (SELECT MIN(ID) GROUP BY STATUS)

这将为您提供以下

SL  STATUS    DATETIME                   
1   STOP      2012-12-19 13:10:00        
2   START     2012-12-19 13:22:00

答案 1 :(得分:0)

SELECT sl,status,min(DATETIME)FROM GROUP BY STATUS

答案 2 :(得分:0)

目前尚不清楚您是如何选择要在结果集中为SLDATETIME选择的值(特别是如果有多个记录具有相同的DATETIME值),但假设它们是最早DATETIME一段不变的STATUS记录的记录:

SELECT my_table.*, t.STOPPAGE
FROM   my_table NATURAL JOIN (
  SELECT   STATUS,
           MIN(DATETIME) AS DATETIME,
           NULLIF(TIMEDIFF(MAX(DATETIME),MIN(DATETIME)),0) AS STOPPAGE
  FROM (
    SELECT   t1.DATETIME, t1.STATUS, MIN(t2.DATETIME) AS next
    FROM     my_table t1 LEFT JOIN my_table t2
          ON t1.DATETIME < t2.DATETIME AND t1.STATUS <> t2.STATUS
    GROUP BY t1.DATETIME, t1.STATUS
  ) t
  GROUP BY next
) t

sqlfiddle上查看。

如果结果集中不需要SL(或者它应该是递增计数器),则可以省略最外面的查询:

SELECT   @sl := @sl + 1 AS SL,
         STATUS,
         MIN(DATETIME) AS DATETIME,
         NULLIF(TIMEDIFF(MAX(DATETIME),MIN(DATETIME)),0) AS STOPPAGE
FROM (
  SELECT   t1.DATETIME, t1.STATUS, MIN(t2.DATETIME) AS next
  FROM     my_table t1 LEFT JOIN my_table t2
        ON t1.DATETIME < t2.DATETIME AND t1.STATUS <> t2.STATUS
  GROUP BY t1.DATETIME, t1.STATUS
) t, (SELECT @sl := 0) init
GROUP BY next
ORDER BY DATETIME

sqlfiddle上查看。