Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not contained in aggregate or group by clause

Tags:

sql

sql-server

Here is the table:

Product(maker, model, type)

The table "Product" includes information about the maker, model number, and type ('PC', 'Laptop', or 'Printer')

Challenge:

Find out makers who produce only the models of the same type, and the number of those models exceeds 1.

What I did:

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

Problem:

Column 'Product.type' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Notes:

In the table, the maker D creates only Printers. So, I want to get:

Maker | Type

D     | Printer

If I remove type from the query I get D, which is what I want, but without type. If I include type in GROUP BY clause I get different result.

Question:

How to fix this?

like image 610
Joe Avatar asked Dec 02 '25 02:12

Joe


1 Answers

SELECT  maker, MIN(type)
FROM    product
GROUP BY
        maker
HAVING  COUNT(DISTINCT type) = 1
        AND COUNT(*) > 1
like image 185
Quassnoi Avatar answered Dec 03 '25 19:12

Quassnoi