【问题标题】:PHP - Calculate running balance [duplicate]PHP - 计算运行余额[重复]
【发布时间】:2022-01-04 18:32:20
【问题描述】:

我正在尝试使用 mysql 编写 php 代码,我想根据交易类型计算运行余额。我的数据库表如下

id  |  amt    |  type    |    date
----+---------+----------+-----------
 1  |   70000 |    Cr    | 01-01-2022
 2  |    8000 |    Dr    | 01-01-2022
 3  |   60000 |    Cr    | 02-01-2022
 4  |   50000 |    Dr    | 02-01-2022
 5  |   90000 |    Cr    | 03-01-2022
 6  |   28000 |    Dr    | 03-01-2022

我希望得到如下结果,如果 type = Cr 然后 ADD,如果 type = Dr 然后 SUBTRACT 并自动计算运行 BALANCE,其中初始值为零

id  |    Dr    |    Cr   |     date    |  balance
----+----------+---------+-------------+----------
 1  |       0  |  70000  |  01-01-2022 |   70000
 2  |    8000  |      0  |  01-01-2022 |   62000
 3  |       0  |  60000  |  02-01-2022 |  122000
 4  |   50000  |      0  |  02-01-2022 |   72000
 5  |       0  |  90000  |  03-01-2022 |  162000
 6  |   28000  |      0  |  03-01-2022 |  134000

以下是我目前正在使用的PHP脚本

<table>
<tr><th>Date</th><th>IN</th><th>OUT</th><th>Balance</th></tr>
<?php
$conn=mysqli_connect("details hidden");

$sql="SELECT * FROM table_name WHERE type IN ('Dr', 'Cr') ORDER BY date DESC";
$query=mysqli_query($conn, $sql);
while ($row=mysqli_fetch_array($query)) {

echo '<tr>';
echo '<td>'.$newdate = date('d-m-y', strtotime($row['date'])).'</td>';

if ($row['type']==Dr){
echo '<td>'.$row['amt'].'</td>';
echo '<td></td>';}

elseif ($row['type']==Cr){
echo '<td></td>';
echo '<td>'.$row['amt'].'</td>';}

else {
echo '<td></td>;
echo '<td></td>;}
echo '</tr>';
}
?>
</table>

任何帮助都会有所帮助。

【问题讨论】:

  • popsql.com/learn-sql/mysql/… 看起来与您的用例非常相似
  • @ADyson 您分享的示例在没有任何条件的情况下计算运行总数,我提出的问题是基于条件('type'列值)。
  • 我认为它可能会为您指明正确的方向,因为您甚至还没有开始......

标签: php html mysql


【解决方案1】:

你可以使用sum窗口函数得到你想要的结果:

select id, 
case when `type` = 'Dr' then `amt` else 0 end as Dr,
case when `type` = 'Cr' then `amt` else 0 end as Cr,
date,
sum(case when `type` = 'Dr' then -`amt` when `type` = 'Cr' then `amt` end) over(order by date rows unbounded preceding) as balance
from table_name;

Fiddle

【讨论】:

    猜你喜欢
    • 2017-04-01
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 2021-10-18
    相关资源
    最近更新 更多