[英]MySQL Query to Subtract 1st column of 1st row with 2nd column of 2nd row
I'm struggling with a Mysql Code, and I have no clue how to solve this. 我正在努力使用Mysql代码,并且不知道如何解决此问题。 I have two columns with time value on which I've ordered by desc in Mysql Query result. 我在Mysql Query结果中按desc排序了两列带有时间值的列。
I need to find out the differences between the 2nd row StateEndTime and the 1st-row StateStarTtime nd so on and display this in a new row/column. 我需要找出第二行StateEndTime和第一行StateStarTtime nd之间的差异,然后将其显示在新行/列中。 The final table should look like this : 决赛桌应如下所示:
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
Assuming ID is an auto increment column, this can be achieved in MySQL by self join technique: 假设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
Is this what you trying to do? 这是您想做的吗?
mysql_query("SELECT *, `StateEndTime`-`StateStarTtime` AS `Min Difference`
FROM `TableName`");
This could be simplified in a MYSQL 8 with CTE and or the ROW_NUM function but this will work to get the solution you are after in most versions. 可以在带有CTE和或ROW_NUM函数的MYSQL 8中简化此操作,但是在大多数版本中,此操作将为您提供所需的解决方案。
I've also casted your times as in the example they arent in the correct format, this may not be the case in your actual data. 我还按照示例说明您的时间,它们以正确的格式显示,但实际数据可能并非如此。
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
Result: 结果:
"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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.