[英]mysql: difference between values in one column
這個董事會過去曾幫我幾次。
我的挑戰:我希望得到一列內的值之間的差異。
該表如下所示:
id | channel_id | timestamp | value
4515| 7 |1519771680000 | 7777
4518| 8 |1519772160000 | 6666
4520| 7 |1519772340000 | 8888
我想做的事:
過濾(例如channel_id = 7)。 計算一個時間戳和下一個時間戳之間的差異。 在此示例中:8888-7777
我在另一個數據庫上找到了一個解決方案但我無法將其轉移到mysql,因為windows函數非常有限。 有人想知道如何獲得可以在select語句中使用的解決方案嗎?
Thx和KR Holger
您可以通過將表連接到自身來獲取要比較(即減去)的兩行:
SELECT
a.channel_id,
a.timestamp,
b.timestamp,
a.value - b.value as `difference`
FROM table a
JOIN table b
ON a.channel_id = b.channel_id and a.timestamp <> b.timestamp and a.value > b.value
GROUP BY a.channel_id
ORDER BY a.channel_id
您可以使用“相關子查詢”,如下所示(另請參閱此演示) 。 當MySQL實現LEAD()
這樣的窗口函數時,你可以使用它們。
MySQL 5.6架構設置 :
CREATE TABLE Table1
(`id` int, `channel_id` int, `timestamp` bigint, `value` int)
;
INSERT INTO Table1
(`id`, `channel_id`, `timestamp`, `value`)
VALUES
(4515, 7, 1519771680000, 7777),
(4518, 8, 1519772160000, 6666),
(4520, 7, 1519772340000, 8888)
;
查詢1 :
select
id
, channel_id
, timestamp
, value
, nxt_value
, nxt_value - value as diff
from (
select
t1.id
, t1.channel_id
, t1.timestamp
, t1.value
, (select value from table1 as t2
where t2.channel_id = t1.channel_id
and t2.timestamp > t1.timestamp
order by t2.timestamp
limit 1) nxt_value
from table1 as t1
) as d
結果 :
| id | channel_id | timestamp | value | nxt_value | diff |
|------|------------|---------------|-------|-----------|--------|
| 4515 | 7 | 1519771680000 | 7777 | 8888 | 1111 |
| 4518 | 8 | 1519772160000 | 6666 | (null) | (null) |
| 4520 | 7 | 1519772340000 | 8888 | (null) | (null) |
從MySQL 8開始,您可以使用窗口函數 ,如果您的查詢如下所示:
SELECT
id, channel_id, timestamp, value,
value - LAG(value, 1, 0) OVER (PARTITION BY channel_id ORDER BY timestamp) difference
FROM my_table
感謝您的支持。 我嘗試了很多,並根據存儲過程創建了“我的”解決方案。 它沒有盡可能高的性能,但它提供了所需的值。
代碼在腳本執行中以最大重復次數循環運行,以避免無休止的步驟:)
#Auswahl größer CH10-Wert
set @var_max_ch10vz =
(
select max(data.timestamp)
from volkszaehler.data
where data.channel_id=10
)
;
#Auswahl kleinster offener Wert aus SBFSPOT
set @var_min_sbfspot =
(
select min(data.timestamp_unix*1000)
from sbfspot_u.data
where
data.timestamp_vzjoin is null
and data.timestamp_unix >1522096327
and data.timestamp_unix*1000 < @var_max_ch10vz
)
;
#Abgleich gegen VZ von unten
set @var_max_vz =
(
select min(data.timestamp)
from volkszaehler.data
where data.channel_id=10 and data.timestamp >= @var_min_sbfspot
)
;
#Abgleich gegen VZ von oben
set @var_min_vz =
(
select max(data.timestamp)
from volkszaehler.data
where data.channel_id=10 and data.timestamp <= @var_min_sbfspot
)
;
#Auswahl join Zeitstempel
set @vz_join_timestamp =
(
select tmp.uxtimestamp
from (
select @var_max_vz as uxtimestamp, abs(@var_min_sbfspot-@var_max_vz) as diff
UNION
select @var_min_vz as uxtimestamp, abs(@var_min_sbfspot-@var_min_vz) as diff
) tmp
order by tmp.diff asc
limit 1
)
;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.