用于查找运行总计的两个值之间的差异

时间:2017-02-18 17:42:01

标签: mysql

我有一张名为" GOLDSTOCKTABLE"

+----------+-------------+----------------+  
!ID ! GRAM !  GRAMTOBANK ! LOCKERBALANCE  !
+----------+-------------+----------------+ 
!1  ! 10   !    9        !                !
!2  ! 15   !    10       !                ! 
!3  ! 8    !    8        !                ! 
!4  ! 45   !    40       !                !
+----------+-------------+----------------+    

在记录的每个条目上,GRAM和GRAMTOBANK之间的差异与LOCKERBALANCE中的累积和一起存储,结果表看起来像

+----------+-------------+----------------+  
!ID ! GRAM !  GRAMTOBANK ! LOCKERBALANCE  !
+----------+-------------+----------------+ 
!1  ! 10   !    9        !    1           !
!2  ! 15   !    10       !    6           ! 
!3  ! 8    !    8        !    6           ! 
!4  ! 45   !    40       !    11          !
+----------+-------------+----------------+  

2 个答案:

答案 0 :(得分:1)

使用变量存储累计和:

select ID, GRAM, GRAMTOBANK
       , @lb := @lb + (GRAM - GRAMTOBANK) as LOCKERBALANCE  
from
    (select @lb := 0) x,
    (select ID, GRAM, GRAMTOBANK
     from GOLDSTOCKTABLE
     order by ID) y

答案 1 :(得分:0)

您可以使用变量执行此操作 - 请注意,在运行主查询之前,必须运行第一个查询以将变量设置为0.

SET @LOCKERBALANCE=0;

SELECT 
  GOLDSTOCKTABLE.*, 
  (@LOCKERBALANCE := @LOCKERBALANCE + (GRAM-GRAMTOBANK)) as LOCKERBALANCE
FROM GOLDSTOCKTABLE
ORDER BY ID