MySQL查询用第二行的第二列减去第一行的第一列

时间:2019-02-02 11:31:04

标签: mysql

我正在努力处理Mysql代码,而且不知道如何解决此问题。我有两列具有时间值的列,这些列是我在Mysql Query结果中按desc排序的。

我需要找出第二行StateEndTime和第一行StateStarTtime nd之间的差异,然后将其显示在新的行/列中。决赛桌应该像这样:

ID          Type         StateStarTtime    StateEndTime   Min Difference

xxx         YYY          03:57             03:59          00:02
xxx         ZZZ          03:53             03:55          00:04
xxx         ZZZ          03:46             03:49          

3 个答案:

答案 0 :(得分:1)

假设ID是一个自动递增列,则可以在MySQL中通过自连接技术来实现:

 SELECT 
  t1.ID,
  t1.Type,
  t1.StateStartTime,
  t1.StateEndTime
  (t1.StateStartTime - t2.StateEndTime) AS Min_Diff
 FROM
 Table1 t1
    INNER JOIN
 Table1 t2 ON t2.id = t1.id + 1

答案 1 :(得分:0)

这是您要做什么吗?

  mysql_query("SELECT *, `StateEndTime`-`StateStarTtime` AS `Min Difference` 
  FROM `TableName`");

答案 2 :(得分:0)

这可以在带有CTE和/或ROW_NUM函数的MYSQL 8中简化,但这将在大多数版本中为您提供所需的解决方案。

我还按照您的时间投放了示例,因为它们没有正确的格式,在您的实际数据中可能并非如此。

SET @row_number_a = 0;
SET @row_number_b = -1;

SELECT a.id, a.type, a.start, a.end, TIMEDIFF(CAST(a.start AS TIME), CAST(b.end AS TIME)) AS DIFF  
FROM
(SELECT (@row_number_a:=@row_number_a + 1) AS num, id, type, start, end
FROM tbl) a

LEFT JOIN (
SELECT (@row_number_b:=@row_number_b + 1) AS num, id, type, start, end
FROM tbl
) b
ON a.num = b.num

结果:

"id"    "type"  "start" "end"   "DIFF"
"xxx"   "YYY"   "03:57" "03:59" "00:02:00"
"xxx"   "ZZZ"   "03:53" "03:55" "00:04:00"
"xxx"   "ZZZ"   "03:46" "03:49" \N