【问题标题】:Calculate running total for each person计算每个人的跑步总数
【发布时间】:2015-04-13 21:45:00
【问题描述】:

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

我已经有这个查询:

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

【问题讨论】:

  • 为什么贷方 5k 在借方 10k 之后和借方 50 之前应用?你用 id 3 添加新的信用是什么?结果应该是什么样子?
  • 这只是要求之一,因为我需要交替显示借方和贷方
  • 问题是我需要每个 studno 都有自己的变量@bal
  • 我们不能,因为#3 应该有一些东西要先支付或借记
  • 我们可以,stud2 支付 50 - 这是 id 2,然后 stud 1 支付 50 - 这是 id 3

标签: mysql sql database cumulative-sum


【解决方案1】:

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

【讨论】:

  • 非常感谢,但是如何隐藏@studno:=studno 列?
  • @BernadineBacolod 查看我更新的答案(我删除了第一个studno,并将其放在最后一列。重要的是更新@studno 之后 @bal,因为否则运行总计将不起作用
【解决方案2】:

正如我在 cmets 中所写 - 现有查询确实交织错误,如果相应应付 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    相关资源
    最近更新 更多