我在mysql中有"P_L“列和" status”列,列中有关于利润或亏损的数字和状态-如果这些数字是正的或负的。
解释: 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";
}发布于 2018-01-09 09:20:14
您可以在MySQL查询using IF()中对P_L列求和
SELECT SUM(IF(Status = 'Profit', P_L, -1 * P_L)) AS profit_and_loss FROM tableName;发布于 2018-01-09 09:12:51
将总数放在循环之外。
创建一个从零开始的占位符/容器,然后根据实际值进行加/减:
请遵循以下代码,将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";https://stackoverflow.com/questions/48160133
复制相似问题