计算每个人的 运行 总数

Calculate running total for each person

我需要在我的数据库中显示每个人的 运行 总数,但我只能得到所有人的 运行 总数,所以这些是我在图片上的表格

我已经有了这个查询:

SELECT 
    id, 
    studno,
    if(type=0,amount,0)debit,
    if(type=1,amount,0)credit,
    if(type=0,@bal:=@bal+amount,@bal:=@bal-amount) runningTotal
FROM
(SELECT id, studno, amount, 0 type from tblPayables 
UNION ALL 
SELECT id, studno, amount, 1 type from tblPayments)s, (SELECT @bal:=0)b
ORDER BY studno, id, type;

但问题是我只能得出这个结果:

突出显示的数字应为 50,因为它用于不同的学号

您必须以每次 ID 更改时初始化变量的方式编写查询。

假设您可以编写包含以下列的查询或视图:

id | studno | debit | credit
---+--------+-------+-------

那么,让我们编写查询:

select id, debit, credit
     , @bal := ( -- If the value of the column `studno` is the same as the
                 -- previous row, @bal is increased / decreased;
                 -- otherwise, @bal is reinitialized
         case 
             when @studno = studno then @bal + debit - credit
             else debit - credit
         end
     ) as balance
     @studno := a.studno as studno -- It's important to update @studno
                                   -- AFTER you update @bal
from 
    (
        select @bal := 0
             , @studno := 0 -- This variable will hold the previous
                            -- value of the `studno` column
    ) as init, -- You must initialize the variables
    ( -- The above mentioned query or view
        select ...
        from ...
    ) as a
order by a.studno, a.id -- It's REALLY important to sort the rows

正如我在评论中所写 - 现有查询交错错误,如果对应的应付 ID 的付款 ID 较小,它将失败

这里是正确交错并计算 运行 总数的查询,正如@Barranka 建议的那样:

select studno, amount, @bal := (
         case 
             when @studno = studno then @bal + amount
             else amount
         end
     ) as balance,
  @studno := studno
from
(
        select @bal := 0
             , @studno := 0
) as init,
(
select 0 as t, studno, amount, (select count(*) from tblPayables as b where a.id>b.id and a.studno=b.studno) as trN
from tblPayables as a
union all
select 1 as t, studno, -amount, (select count(*) from tblPayments as b where a.id>b.id and a.studno=b.studno) as trN
from tblPayments as a
) as q
order by studno, trN, t

http://sqlfiddle.com/#!2/9e0cf1/1