Mysql - 获取两个连续值之间的差异

时间:2015-02-11 20:36:49

标签: mysql sql sequential

我希望从我的表中获得两个连续值之间的差异。

| id | count |
| 1  |   1   |
| 2  |   7   |
| 3  |   9   |
| 4  |   3   |
| 5  |   7   |
| 6  |   9   |

例如

之间的区别

id2-id1 = 6,
id3-id2 = -2
 ...

我该怎么办? SELECT SUM(id(x+1) - id(x)) FROM table1

4 个答案:

答案 0 :(得分:1)

如果您知道 ids没有间隙,那么只需使用join

select t.*, (tnext.count - t.count) as diff
from table t join
     table tnext
     on t.id = tnext.id - 1;

如果您只想要差异的总和,那么这与最后一个值减去第一个值相同(所有中间值在求和中抵消)。您可以使用limit

执行此操作
select last.count - first.count
from (select t.* from table order by id limit 1) as first cross join
     (select t.* from table order by id desc limit 1) as last;

答案 1 :(得分:1)

您可以使用子查询查找前一个count的{​​{1}}。

如果id列中没有空白:

ID

SQLFiddle

如果SELECT CONCAT(t.`id` ,' - ', t.`id` - 1) AS `IDs` , t.`count` - (SELECT `count` FROM `tbl` WHERE `id` = t.`id` - 1) AS `Difference` FROM `tbl` t WHERE t.`id` > 1 列中存在空白。 第一个解决方案ID使用ORDER BY <...> DESC

LIMIT 1

SQLFiddle

第二个解决方案,使用其他子查询查找SELECT CONCAT(t.id ,' - ', (SELECT `id` FROM tbl WHERE t.id > id ORDER BY id DESC LIMIT 1)) AS IDs , t.`count` - (SELECT `count` FROM tbl WHERE t.id > id ORDER BY id DESC LIMIT 1) AS difference FROM tbl t WHERE t.id > 1; count小于当前MAX(id)

id

SQLFiddle

P.S。 :第一列SELECT CONCAT(t.id ,' - ', (SELECT MAX(`id`) FROM tbl WHERE id < t.id)) AS IDs , t.`count` - (SELECT `count` FROM tbl WHERE `id` = (SELECT MAX(`id`) FROM tbl WHERE id < t.id) ) AS difference FROM tbl t WHERE t.id > 1; 仅用于提高可读性,如果有必要,您可以省略或完全更改。

答案 2 :(得分:0)

试试这个:

SELECT MAX(count)-MIN(count) diff WHERE id IN(1,2)

或者这样

SELECT 2*STD(count) diff WHERE id IN(1,2)

答案 3 :(得分:0)

即使 ID之间有距离

,这也有效
SELECT *, 
  ((SELECT value FROM example e2 WHERE e2.id > e1.id ORDER BY id ASC LIMIT 1) - value) as diff
FROM example e1;