计算每个人的跑步总数

时间:2015-02-12 23:07:44

标签: mysql sql database running-total

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

我已经有了这个问题:

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,因为它是针对不同的studno

2 个答案:

答案 0 :(得分:2)

您必须以每次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

答案 1 :(得分:0)

正如我在评论中写的那样 - 现有查询交错错误,如果相应应付帐户的付款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