我有以下结构的表
var label = options.filter(el => el.value === 'mac')[0].label;
我想要这样的输出
ID VALUE
1 100
2 200
3 300
4 400
5 500
这是我到目前为止尝试的查询
ID VALUE DIFF_to_Prev
1 100 0
2 200 100
3 300 100
4 400 100
5 500 100
这是我得到的结果:
SET @LastVALUE:= 0;
SET @LastSN:= 0;
SELECT dtr.SN, dtr.VALUE,
IF(@LastSN = dtr.SN, dtr.Value - @LastVALUE, 0) DIFF_to_Prev
FROM difftworows as dtr
我想知道我做错了什么。请告诉我如何通过建议修复它。
谢谢!
答案 0 :(得分:6)
当然你在这一列中得到0,你没有给参数任何值..
如果ID是连续的,3将始终是4的前一个,4中的4和ETC ......那么可以通过连接来完成:
SELECT t.id,t.value,t.value-coalese(s.value,0) as DIFF_to_Prev
FROM YourTable t
LEFT OUTER JOIN YourTable s ON(t.id = s.id + 1)
答案 1 :(得分:3)
E.g:
SELECT x.*
, COALESCE(x.value-@prev,0) diff_to_prev
, @prev:=value
FROM my_table x
, (SELECT @prev:=null) vars
ORDER
BY id;
答案 2 :(得分:2)
SET @LastVALUE:= 0;
SELECT dtr.ID, dtr.VALUE,
0 - @LastVALUE + (@LastVALUE := dtr.VALUE) DIFF_to_Prev
FROM difftworows as dtr
ORDER BY dtr.ID
如果第一个Diff确实需要为0:
SET @LastVALUE:= NULL;
SELECT dtr.ID, dtr.VALUE,
CASE
WHEN @LastVALUE IS NULL THEN 0 * (@LastVALUE := dtr.VALUE)
ELSE 0 - @LastVALUE + (@LastVALUE := dtr.VALUE)
END DIFF_to_Prev
FROM difftworows as dtr
ORDER BY dtr.ID
答案 3 :(得分:1)
不使用用户变量
SELECT sub0.ID,
sub0.VALUE,
sub0.VALUE - (COALESCE(d2a.VALUE, sub0.VALUE)) AS DIFF_to_Prev
FROM
(
SELECT d1.ID, d1.VALUE, MAX(d2.ID) AS d2_max_id
FROM difftworows d1
LEFT OUTER JOIN difftworows d2
ON d1.ID > d2.ID
GROUP BY d1.ID, d1.VALUE
) sub0
LEFT OUTER JOIN difftworows d2a
ON sub0.d2_max_id = d2a.ID
ORDER BY sub0.ID
编辑 - 避免子查询: -
SELECT d1.ID,
d1.VALUE,
d1.VALUE - IF(COUNT(d2.ID) = 0, d1.VALUE, SUBSTRING_INDEX(GROUP_CONCAT(d2.VALUE ORDER BY d2.ID DESC), ',', 1)) AS DIFF_to_Prev
FROM difftworows d1
LEFT OUTER JOIN difftworows d2
ON d1.ID > d2.ID
GROUP BY d1.ID,
d1.VALUE
答案 4 :(得分:0)
我会恢复它,因为现在有更好的方法来做到这一点 - 在 mysql 8+ 中,有针对此类问题的窗口函数。对于这种情况,您可以使用延迟,如下所示: https://learnsql.com/blog/difference-between-two-rows-in-sql/
对你来说:
VALUE - LAG(VALUE) OVER (ORDER BY ID ) AS DIFF_to_Prev