-4

如何查询

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

我必须将日期值之间的差异作为状态为STOP的STOPPAGE

4

3 回答 3

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
于 2012-12-19T12:50:39.047 回答
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上查看。

于 2012-12-19T13:49:53.193 回答
0

从 GROUP BY STATUS 中选择 sl,status,min(DATETIME)

于 2012-12-19T12:56:36.407 回答