我有专栏" P_L"在mysql中有关于损益的数字和列"状态"状态 - 如果这些数字是正面的或负面的。
说明:50利润= + 50,30损失= - 30
我试图计算这些数字以获得总利润/亏损,但有些东西不起作用。下面的代码输出是:+ 50 - 30 + 50 - 25 - 15
那么,如何计算P_L列?这样的事情甚至可能吗?
谢谢!
表格看起来像这样:
+-------+---------------+--------+-----------+
| Id | Date Added | P_L | Status |
+-------+---------------+--------+-----------+
| 1 | 2017-12-2 | 50 | Profit |
| 2 | 2017-12-3 | 30 | Loss |
| 3 | 2017-12-4 | 50 | Profit |
| 4 | 2017-12-5 | 25 | Loss |
| 5 | 2017-12-6 | 15 | Loss |
+-------+---------------+--------+-----------+
我的PHP代码..
.
.
.
while($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$date_added = $row['date_added'];
$p_l = $row['p_l'];
$status = $row['status'];
if($status == 'Profit') {
$number = "+ $p_l";
} elseif($status == 'Loss') {
$number = "- $p_l";
}
$total = $number . " ";
echo "$total";
}
答案 0 :(得分:1)
您可以在MySQL查询using IF()中对P_L列求和:
SELECT SUM(IF(Status = 'Profit', P_L, -1 * P_L)) AS profit_and_loss FROM tableName;
答案 1 :(得分:0)
将总数放在循环之外。
创建一个从零开始的占位符/容器,然后根据实际值加/减:
遵循以下代码,由于您未提供表格结构,因此将p_l
列转换为floatval()
。
$total = 0; # placeholder
while($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$date_added = $row['date_added'];
$p_l = $row['p_l'];
$status = $row['status'];
$number = floatval($p_l);
if($status == 'Profit') {
$total = $total + $number;
} elseif ($status == 'Loss') {
$total = $total - $number;
}
}
echo "$total";