我想從我的表中獲取兩個連續值之間的差異。Mysql - 獲取兩個連續值之間的差異
| 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
我想從我的表中獲取兩個連續值之間的差異。Mysql - 獲取兩個連續值之間的差異
| 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
您可以使用子查詢找到count
的前id
。
在情況下,存在在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
在情況下,存在在ID
柱的間隙。 首先解決,使用ORDER BY <...> DESC
與LIMIT 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;
解決方法二,使用其它子查詢中找到count
與MAX(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;
P.S. :第一列IDs
僅供閱讀,如果有必要,您可以忽略它或完全更改。
如果您知道的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;
試試這個:
SELECT MAX(count)-MIN(count) diff WHERE id IN(1,2)
還是這樣
SELECT 2*STD(count) diff WHERE id IN(1,2)
這個工程即使IDS有它們之間的距離:
SELECT *,
((SELECT value FROM example e2 WHERE e2.id > e1.id ORDER BY id ASC LIMIT 1) - value) as diff
FROM example e1;
你可能想看看HTTP://計算器。com/questions/20849098/mysql-how-get-value-in-previous-row-and-value-in-next-row will help out。 – 2015-02-11 20:40:24