Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP BY and COUNTs not producing expected results

Tags:

sql

group-by

I am doing some SQL exercises, but I'm stuck in the one I'll describe.

There is a table called product that has 3 columns: maker, model and type.

This is the result of select * from product

enter image description here

The excercise says this: Find out makers who produce only the models of the same type, and the number of those models exceeds 1. Deduce: maker, type.

The correct query should return this:

enter image description here

My approach was to first see which makers made only one type of product and then exclude those makers who have only one model. To do that I used the following query, and it returns the correct result, except for the fact that I can only manage to display the maker, but not the type and the exercise asks for both.

This is my query:

SELECT
DISTINCT maker
FROM product
GROUP BY maker
HAVING COUNT(distinct type) = 1 
AND
COUNT(model)> 1

And it returns this:

enter image description here

then, when I try to display the type as well by doing this:

SELECT
DISTINCT maker,type
FROM product
GROUP BY maker,type
HAVING COUNT(distinct type) = 1 
AND
COUNT(model)> 1

this is what I get:

enter image description here

Do you have any idea of why this is not working as expected? What would you do to solve this problem? I've been trying to solve this for over 3 hours with no success. :( Help me please.

like image 594
Alex Terreaux Avatar asked Jan 03 '13 17:01

Alex Terreaux


2 Answers

If you are only returning those groups containing exactly one type you can just use MAX/MIN to find out what the type in that group is.

SELECT maker,
       MAX(type) AS type
FROM   product
GROUP  BY maker
HAVING COUNT(DISTINCT type) = 1
       AND COUNT(model) > 1 

When you add type into the GROUP BY list it will give you a result row for every combination of maker,type which is why your second attempt doesn't work.

like image 106
Martin Smith Avatar answered Oct 13 '22 21:10

Martin Smith


SELECT DISTINCT maker, type 
FROM product 
WHERE maker IN 
   (SELECT DISTINCT maker 
    FROM product 
    GROUP BY maker HAVING COUNT(distinct type) = 1
    AND count(model) > 1)
like image 44
dghelani Avatar answered Oct 13 '22 21:10

dghelani