I have a table containing data stored like:
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
I want to retrieve all data that matches first word (eg ASIZ ) sum the quantities and display them like:
BUYER1
Asiz - 60 pcs.
Cerveza = 30 pcs.
etc.
BUYER2
Asiz = 48 pcs.
Cerveza = 15 pcs.
etc
at the moment I am using 2 while loops:
SELECT DISTINCT product_name
FROM my_table
WHERE buyer_code= '".$bcode."'
GROUP BY product_name
-- and I get the product names
then
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
I get the sums right, but it lists them every time it finds similar named products (eg: BUYER1: ASIZ - 2 times etc.)
it shows:
Buyer1
ASIZ - 60
Cerveza - 30
ASIZ - 60
Cerveza - 30
I know it has something to do with the product_name, but how should I write the sql statement to work? Thanks
SELECT SUBSTRING_INDEX(product_name, '.', 1) product, tert, SUM(quantity) quantity
FROM my_table
GROUP BY product, tert
Remove tert
from your second sql and it would work as expected.
Change this to
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
this
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
Run
SELECT tert, SUBSTRING_INDEX(product_name,' ',1) as product, sum(quantity) as qty
FROM my_table
GROUP BY tert, product
ORDER BY tert, product
Your results are sorted by tert so ou can walk through one by one showing product and qty and displaying tert every time a tert changes.
UPDATE : A code sample how to output the data (not tested):
$tert = null;
foreach($rows as $row){
if($rows['tert'] != $tert){
$tert = $rows['tert'];
echo $tert;
}
echo $row['product'], "-", $row['qty'];
}
here $rows
- all fetched rows.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.