2015-02-11 75 views
1

我想從我的表中獲取兩個連續值之間的差異。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

+0

你可能想看看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

回答

1

您可以使用子查詢找到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 

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僅供閱讀,如果有必要,您可以忽略它或完全更改。

+0

但如果ID有空隙 – dasdasd 2015-02-11 21:01:09

+0

@dasdasd:更新 – potashin 2015-02-11 21:25:42

+1

謝謝,幫了我很多。 – dasdasd 2015-02-11 22:04:11

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; 
0

試試這個:

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

還是這樣

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

這個工程即使IDS有它們之間的距離:

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