douqiao8032 2013-05-13 12:29
浏览 110
已采纳

显示适当的余额,按降序显示MySQL行

I have a query that is supposed to show deposits, withdrawls, and balance. I am summing the deposits and withdrawls to get the balance.

The query and display works ok when ORDER BY date ASC.

However, I wish to order by DESC and this is causing issues with the display of balance. Here is an example.

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

As you can see I would want the Jan 1 balance to be 5000 and the Jan 2 balance to be 3000. I'm stuck on a good way to solve this. At first, I simply created a column for balance and inserted the balance as the row was being written. But this caused problems when a single row was updated.

Any help appreciated! Thanks.

Here is the code I'm working with.

$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

}
  • 写回答

3条回答 默认 最新

  • douwen0612 2013-05-13 13:06
    关注
    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探