Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SELECT with GROUP BY and HAVING in a specific SQL case

I have an SQL database with one table: Product (maker, type, model)

For each row we have a different maker (brand), a type of product(pc, tablet, laptop, etc.) and a model (1.1 / 2.0 / 3.4.5 etc)

Q: How do I get the makers who produce only one product type and more than one model.

Output: maker, type.

Hints: GROUP BY and HAVING statements

I tried the following query, but it didn't work out, as it was not returning any value in the resulting table:

SELECT
maker, type
FROM
product
GROUP BY maker, type
HAVING count(model)>1 and count(type)=1

What am I doing wrong in this SELECT? Thank you very much!

like image 782
Victor A Avatar asked Dec 06 '25 03:12

Victor A


1 Answers

You were very close:

SELECT maker, MIN(type) type
FROM product
GROUP BY maker
HAVING COUNT(DISTINCT type) = 1
AND COUNT(DISTINCT model) > 1;
like image 96
Lamak Avatar answered Dec 09 '25 18:12

Lamak



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!