I'm using MySQL 5.0.88/Coldfusion8
and I have a table that contains products based on barcodes/EANs.
So a product 123 in size S,M,L,XL
will have four records in the table
product size ean qty disregard_inventory
123 S 1111111111111 5 0
123 M 1111111111112 7 0
123 L 1111111111113 1 0
123 XL 1111111111114 2 0
Right now I'm searching this table like so:
SELECT count(a.id) AS total_records, a.disregard_inventory, a.qty
FROM artikelstammdaten a
...
GROUP BY a.style
HAVING sum(a.qty) != 0 OR (a.disregard_inventory = 1)
This works ok and selects all products which are not sold out (sum > 0 across all eans)/always available
I now want to add a function, so users can search for products that have at least 1pc in each size. In this case, style 123
123 S 1
123 M 0
123 L 12
123 XL 9
would not be included in the resultset as size M
is sold out.
However I can't get it to work. This is what I have (produces rubbish):
GROUP BY a.style
<cfif form.select_type EQ "running_sizes">
HAVING a.qty!= 0 OR ( a.disregard_inventory = 1 )
<cfelse>
HAVING sum(a.bestand) != 0 OR (a.disregard_inventory = 1)
</cfif>
Question:
Is it at all possible to group by style
and only include style
when each underlying ean
has a quantity > 0? If so, thanks for pointers!
EDIT:
here is my full query, which I'm testing with:
SELECT count(a.id) AS gesamt_datensaetze, a.nos, a.nos_anzeige, a.bestand, SUM(a.bestand>0) AS what
FROM artikelstammdaten a
WHERE a.aktiv = "ja"
AND a.firma LIKE "some_company"
// groups by seller_id, style
GROUP BY a.iln, a.artikelnummer
HAVING sum(a.bestand) != 0 OR (a.nos = "ja" AND a.nos_anzeige = "ja")
AND ( SUM(a.bestand > 0) = COUNT(*))
Solution:
Partenthesis mising:
HAVING (( sum(a.bestand) != 0 ) OR (a.nos = "ja" AND a.nos_anzeige = "ja" ))
AND ( SUM(a.bestand > 0) = gesamt_datensaetze )
This works.
You can accomplish this using a join on a subquery. Basically, join on the set of product IDs where the quantity available is zero, and then only return results where there was no match.
I think you should check MIN(a.qty):
I suggest the following query:
The last condition I added to the query enables to return a style only if the number of sizes for this product (
total_records
) is equal to the number of available sizes for this product (SUM(qty>0)
).qty>0
will either return 0 (when the product is not available in the given size, or 1 (when it is available). SoSUM(qty>0)
will return an integer number between 0 and the total number of sizes.