Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by x where y = A and B and C

Tags:

mysql

group-by

I have a table that stores product price information. It has a column for the product ID, a quantity and a discount. (Users buys 2 gets £1 off, buys 3 gets £2 off etc).

I'd like to pull all products that have specific quantity discounts associated with them. For example only products that have £5, £10 and £20 off buying 1,2 or 3 respectively.

How can I do that?

I want to group by product ID where there is are three rows that match my criteria - and no other products.

like image 667
William Doherty Avatar asked Dec 02 '25 16:12

William Doherty


2 Answers

Not tested (depends on your schema) but here's the idea:

SELECT P.id, count(P.id)
FROM products P
  LEFT JOIN discounts D ON P.id = D.product_id
WHERE
  (D.quantity = 1 AND D.amount = 5)
  OR (D.quantity = 2 AND D.amount = 10)
  OR (D.quantity = 3 AND D.amount = 20)
GROUP BY P.id
HAVING count(P.id) = 3
like image 188
Frosty Z Avatar answered Dec 04 '25 04:12

Frosty Z


This is the query for SQL Server, there might be a couple tweaks for MySql, but this is the basics.

SELECT * FROM <TABLE> WHERE ProductId in
(SELECT ProductId
FROM <TABLE>
GROUP BY ProductId
HAVING COUNT(ProductId) = 3)
like image 25
taylonr Avatar answered Dec 04 '25 04:12

taylonr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!