2

我有一个查询应该显示存款、取款和余额。我将存款和取款相加以获得余额。

ORDER BYdate时查询和显示工作正常ASC

但是,我希望按顺序订购DESC,这会导致余额显示出现问题。这是一个例子。

Date   Deposit   Withdrawl   Balance
Jan 2            $2000       -$2000
Jan 1  $5000                 $3000

如您所见,我希望 1 月 1 日的余额为 5000,而 1 月 2 日的余额为 3000。我一直坚持解决这个问题的好方法。起初,我只是为余额创建了一个列,并在写入行时插入了余额。但这会在更新单行时引起问题。

任何帮助表示赞赏!谢谢。

这是我正在使用的代码。

$result2 = mysql_query("SELECT * FROM bankaccount_transaction WHERE bankaccount_id = '$id' ORDER BY ID DESC ".$pages->get_limit()) or die(mysql_error());

while($row2 = mysql_fetch_array($result2)) {
$date = date('m-d-Y', strtotime($row2['date']));

if ($row2['deposit'] > 0){
$deposit = $row2['deposit'];
$newdeposit = number_format($deposit,2);
$newtotal += $deposit;
}else{
$newdeposit = '';
}

if ($row2['withdrawl'] > 0){
$withdrawl = $row2['withdrawl'];
$newwithdrawl = number_format($withdrawl,2);
$newtotal -= $withdrawl;
}else{
$newwithdrawl = '';
}

display table

}
4

3 回答 3

2
SELECT x.*
     , SUM(y.deposit)-SUM(y.withdrawal) Balance 
  FROM transactions x 
  JOIN transactions y 
    ON y.bankaccount_id = x.bankaccount_id
   AND y.date <= x.date
 WHERE x.bankaccount_id='$id' 
 GROUP 
    BY x.date 
 ORDER 
    BY Date DESC;

Here's a fiddle

于 2013-05-13T13:06:17.170 回答
1

如果没有有关您的问题的更多信息,我会说您希望将余额与每笔交易一起存储在数据库中。否则,要计算任何时间点的余额或当前余额,您总是必须对数据库中的每一行进行加载和求和。

于 2013-05-13T12:36:36.743 回答
1

我正在考虑做这样的事情:

SELECT 
    m.`date`, 
    m.`deposit`, 
    m.`withdrawal`,
    SUM(t.`deposit`) - SUM(t.`withdrawal`) AS `balance`
FROM `bankaccount_transaction` m 
    JOIN (
            SELECT 
                `date`,
                `deposit`,
                `withdrawal`
            FROM 
                `bankaccount_transaction`
        ) t ON t.`date` <= m.`date`
GROUP BY 
    m.`date`, 
    m.`deposit`, 
    m.`withdrawal`
ORDER BY m.`date` DESC

我想看看我是否可以开始小提琴。

编辑:给你:http ://sqlfiddle.com/#!2/8d040/9

于 2013-05-13T12:55:53.427 回答