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

Mysql - Get the difference between two sequential values

我想从我的 table 中获取两个连续值之间的差异。

| 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

如果您知道 ID 没有间隔,那么只需使用 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;

您可以使用子查询为前面的 id.

查找 count

如果 ID 列中没有空白:

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

SQLFiddle

万一ID栏中有空白。 第一个解决方案,使用 ORDER BY <...> DESCLIMIT 1:

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;

SQLFiddle

第二个解决方案,使用另一个子查询查找 countMAX(id) 小于当前 id:

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;

SQLFiddle

P.S。 : 第一列 IDs 只是为了便于阅读,如有必要,您可以省略或完全更改。

试试这个:

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

或者这样

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

即使 id 之间有距离:

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