如何将两个数据库记录合并为一个并对数量求和?

时间:2018-03-24 08:00:09

标签: php sql

如何将重复记录记录为一个,QUANTITY将根据下图将总数记录为3

screenshot

这是代码:

$id=$_GET['invoice'];
include('connect.php');
$result = $db->prepare("SELECT * FROM sales_order WHERE invoice= :userid");
$result->bindParam(':userid', $id);
$result->execute();

for ($i=0; $row = $result->fetch(); $i++) {

1 个答案:

答案 0 :(得分:1)

您应该在查询中使用SUM()GROUP BY

SELECT SUM(Quantity), `Product Code`, 
`Brand Name`, `Description Name`, `Price`, `Discount`, `VAT`, `Ammount`, 
`Total Amount`
FROM sales_order WHERE invoice=:userid 
GROUP BY `Product Code`, `Brand Name`, `Description Name`

您还可以执行以下操作:

SELECT *, SUM(Quantity)
FROM sales_order WHERE invoice=:userid
GROUP BY `Product Code`, `Brand Name`, `Description Name`