使用Mysql的客户和Grand Total

时间:2014-10-12 22:39:10

标签: php mysql mysqli

让MySQL在这个项目上与我合作有些麻烦。我有一个Order表,其中包含Name,OrderTime,Quantity,CoffeeType和Price。我需要打印一次客户名称,该客户的所有订单,每个客户的小计以及总计。我尝试用两个嵌套的while循环来做,但是这会导致无限循环。我想要的格式是:

Customer Name:

Ordered 10/12/13 1 Espresso 2.00

Ordered 10/11/13 1 Espresso 2.00

Customer Subtotal: 4.00

Grand Total 4.00


$all = mysqli_query($mysqli, "SELECT * FROM orders ORDERBY name");
$result = mysqli_query($mysqli, 
"SELECT *, SUM(Price) as Total FROM orders GROUP BY Name WITH ROLLUP");

while($row = mysqli_fetch_array($result)) {
        echo "Orders for: " . $row["Name"] . "<br>";
        $data = mysqli_fetch_array($all);
        while($data["Name"] === $row["Name"]) {
            echo "On " . $row["OrderTime"] . " ordered " . $row["Quantity"] . " " . $row["CoffeeType"] . " Total: " . asDollars($row["Price"]) . "<br>";
        }
        echo "Customer Total: " . $row["Total"];
        if($row["Name"] === NULL) echo "Grand Total: " . $row["Total"];
}

我知道嵌套while循环可能不是最佳解决方案。我会知道如何在LINQ中使用lambda语句执行此操作,但我不确定MySQL是否具有此功能。有没有办法修复此代码,以实现上述格式?非常感谢您的时间。

1 个答案:

答案 0 :(得分:1)

您可以使用group_concat()之类的

在一个查询中执行此操作
select customer_name,
group_concat(orders) as all_order,
sum(price) as total_price
from Order
group by customer_name