mysql 实现相邻两条数据相减

查询数据

SELECT 
a.`STORE_ID` AS id,
a.`STORE_NAME` AS NAME,
a.`DEPOSIT` AS curr,
@a.DEPOSIT AS pre,        //上一条记录的deposit值
@a.DEPOSIT:= a.DEPOSIT AS tmp
FROM stock_store_addinfo a,(SELECT @a.DEPOSIT:=0)s
  1. @a.DEPOSIT:=a.DEPOSIT AS tmp 将a.DEPOSIT值赋到临时临时变量 @a.DEPOSIT
  2. SELECT @a.DEPOSIT:=0 选择当前表,上一条记录 a.DEPOSIT,默认值为0

mysql 实现相邻两条数据相减_第1张图片

实现差值

SELECT 
b.id,
b.NAME,
b.curr,
b.pre,
(b.curr - b.pre) AS diff
FROM
(
SELECT 
a.`STORE_ID` AS id,
a.`STORE_NAME` AS NAME,
a.`DEPOSIT` AS curr,
@a.DEPOSIT AS pre,
@a.DEPOSIT:= a.DEPOSIT
FROM stock_store_addinfo a,(SELECT @a.DEPOSIT:=0)r
)b

mysql 实现相邻两条数据相减_第2张图片

你可能感兴趣的:(Mysql)