How to write a SQL statement for listing all Makes
that have more than three Types
below is the table of data
Make Model Type
Chrysler Crossfire 2dr Sports
Ford Crown Victoria 4dr Sedan
Ford Crown Victoria LX 4dr Sedan
Ford Crown Victoria LX Sport 4dr Sedan
Honda CR-V LX SUV
Cadillac CTS VVT 4dr Sedan
Dodge Dakota Club Cab Truck
Dodge Dakota Regular Cab Truck
Cadillac Deville 4dr Sedan
Cadillac Deville DTS 4dr Sedan
Mitsubishi Diamante LS 4dr Sedan
Land Rover Discovery SE SUV
Dodge Durango SLT SUV
Mercedes-Benz E320 Wagon
Mercedes-Benz E320 4dr Sedan
Mercedes-Benz E500 Wagon
You need to group your rows by make
& type
and then use having
in your sql. something like this:
SELECT make FROM cars
GROUP BY make
HAVING COUNT(type) > 3
HAVING
is like WHERE
when grouping
EDIT: removed type
column from GROUP BY
Use the following query
SELECT make FROM cars
GROUP BY make
HAVING COUNT(type) > 3
Side Note: In general, All column names in SELECT list must appear in GROUP BY clause unless name is used only in an aggregate function
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.
Learn more about Group BY
in this link
I assume you mean more than three different types. So use COUNT DISTINCT
in the HAVING
clause:
SELECT make
FROM cars
GROUP BY make
HAVING COUNT(DISTINCT type) > 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.