【问题标题】:PHP sum with same reference number具有相同参考编号的 PHP 总和
【发布时间】:2017-03-30 03:22:53
【问题描述】:

首先,我有一个名为 store_00 的表

id | ref | item | qty | cost | sell 
1     22    x1     5     10     15
2     22    x2     10    5      10
3     23    x11    2     4      6
4     23    x22    1     5      10
5     24    x8     1     1      2

现在我希望输出是这样的:

             | ref number 22 |
total cost = 100 | total sell = 175 | total qty = 15

             | ref number 23 |
total cost = 13  | total sell = 22 | total qty = 3

等等……

请注意,我必须将每个成本乘以它的数量,因为上表显示的是单价...这就是我的整个代码混乱的原因,如果我这样做会更容易@ 987654325@!但在我的情况下,结果会有所不同。

PHP 代码:

$query2 = "SELECT * from store_00 GROUP by ref";
$result2 = mysql_query($query2);
While($row2 = mysql_fetch_assoc($result2)){

$ts = $row2['sell'] * $row2['qty'];
$ta = $row2['cost'] * $row2['qty'];
$sumts += $ts;
$sumta += $ta;
$sumqty += $row2['qty'];

echo "<table width=60% height=% align=center border=1 bgcolor=#FFFF99>";

echo "<tr><td align=center><font style='font-size:17px; font-weight:bold;'>TTL QTY = ".$sumqty."</font></td>";
echo "<td align=center><font style='font-size:17px; font-weight:bold;'>TTL Cost = ".number_format($sumta, 2, '.', '')." JD</font></td>";
echo "<td align=center><font style='font-size:17px; font-weight:bold;'>TTL Sell = ".number_format($sumts, 2, '.', '')." JD</font></td></tr>";
echo "</table>";

}

根据上面的代码,输出似乎只取每个分组引用的第一个值,如下所示:

     | ref number 22 |
total cost = 50 | total sell = 75 | total qty = 5

我不知道如何找到一种方法来将值相乘,然后将它们汇总并一次分组引用,如果您有不同的方法,请分享!

【问题讨论】:

  • 我试过了,但没用,只显示空表:/。虽然它看起来对我来说是正确的。
  • 谢谢伙计,它就像一个魅力!
  • 警告:@fusion3k 的答案在大多数 RDMS 中都会失败。聚合查询不应包含未在 group by 中指定的单元级别。要获得真正的 ANSI 答案,请删除小提琴答案中的星号。 MySQL 5.7 中的默认模式包括 full group by

标签: php mysql select sum html-table


【解决方案1】:

可以对两列的乘积使用 SUM。

SELECT
    ref,
    SUM(qty) as total_quantity,
    SUM(qty*cost) as total_cost,
    SUM(qty*sell) as total_sell
FROM `store_00` 
GROUP BY ref

如果您使用此查询,则无需在 PHP 中进行任何数学运算。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    相关资源
    最近更新 更多