2

我有一个包含存储数据的表,例如:

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.

ETC

目前我正在使用2个while循环:

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语句才能工作?谢谢

4

3 回答 3

1
SELECT SUBSTRING_INDEX(product_name, '.', 1) product, tert, SUM(quantity) quantity
FROM my_table
GROUP BY product, tert
于 2012-08-31T12:57:38.847 回答
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
于 2012-08-31T12:59:56.907 回答
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- 所有获取的行。

于 2012-08-31T13:08:46.293 回答