我有一个包含数据的表格,如:
product_name | quantity | tert
ASIZ A4 100 FOX | 20| BUYER1
CERVEZA A6 150 FOX | 15| BUYER1
ASIZ A4 150 FOX | 40| BUYER1
CERVEZA A6 11 FOX | 15| BUYER1
QUINTA A6 150 FOX | 15| BUYER2
ASIZ A4 150 FOX | 33 | BUYER2
ASIZ A6 150 FOX | 15| BUYER2
CERVEZA A6 150 FOX | 15| BUYER2
我想检索与第一个单词匹配的所有数据(例如 ASIZ )对数量求和并显示如下:
BUYER1
Asiz - 60 pcs.
Cerveza = 30 pcs.
etc.
BUYER2
Asiz = 48 pcs.
Cerveza = 15 pcs.
等
目前我正在使用2个循环:
SELECT DISTINCT product_name
FROM my_table
WHERE buyer_code= '".$bcode."'
GROUP BY product_name
- 我得到产品名称
然后
SELECT DISTINCT product_name,tert, SUM(quantity) AS quantity
FROM my_table
WHERE buyer_code ='".$bcode."' AND
prouct_name LIKE '".$first_word_of_product_name."%'
GROUP BY tert
ORDER BY data ASC
我得到了正确的金额,但每当它找到类似的命名产品时就会列出它们(例如: BUYER1:ASIZ - 2次等)
它显示:
Buyer1
ASIZ - 60
Cerveza - 30
ASIZ - 60
Cerveza - 30
我知道它与product_name有关,但是我应该如何编写sql语句呢? 谢谢
答案 0 :(得分:1)
SELECT SUBSTRING_INDEX(product_name, '.', 1) product, tert, SUM(quantity) quantity
FROM my_table
GROUP BY product, tert
答案 1 :(得分:0)
从第二个sql中删除tert
,它将按预期工作。
将此更改为
SELECT DISTINCT product_name,tert, SUM(quantity) AS quantity
FROM my_table
WHERE buyer_code ='".$bcode."'
AND prouct_name LIKE '".$first_word_of_product_name."%'
GROUP BY tert
ORDER BY data ASC
此
SELECT DISTINCT product_name, SUM(quantity) AS quantity
FROM my_table
WHERE buyer_code ='".$bcode."'
AND prouct_name LIKE '".$first_word_of_product_name."%'
GROUP BY product_name
ORDER BY data ASC
答案 2 :(得分:0)
运行
SELECT tert, SUBSTRING_INDEX(product_name,' ',1) as product, sum(quantity) as qty
FROM my_table
GROUP BY tert, product
ORDER BY tert, product
您的结果按 tert 排序,因此您可以逐个展示产品和数量并显示 tert 每次 tert 改变。
<强>更新强>: 代码示例如何输出数据(未测试):
$tert = null;
foreach($rows as $row){
if($rows['tert'] != $tert){
$tert = $rows['tert'];
echo $tert;
}
echo $row['product'], "-", $row['qty'];
}
此处$rows
- 所有已获取的行。