Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sub Grouping Select Statement

Status
Not open for further replies.

SM777

Technical User
Mar 7, 2001
208
GB
I have a database which lists car manufacturers and their models. How can I retrieve data such that each manufacturer is listed as well as the number of models?

Data
-----
Ford, Taurus
Ford, Escort
Ford, P350
Mitsubishi, Evo-7
Nissan, 350Z
Nissan, Skyline GT-R

Required Report
---------------
Ford 3 models
Nissan 2 models
Mitsubishi 1 model

?
 
How about:
[tt]
SELECT manufacturer,COUNT(*)
FROM cars
GROUP BY manufacturer
[/tt]


-----
ALTER world DROP injustice, ADD peace;
 
Hmm, all that does is give me the totals for each manufacturer - not their number of unique models.

I forget to add that the cars database contains many records:

Ford, Taurus
Ford, Taurus
Ford, Escort
Ford, Taurus
Ford, P350
Ford, Escort
Mitsubishi, Evo-7
Mitsubishi, Evo-7
Nissan, 350Z
Nissan, 350Z
Nissan, Skyline GT-R
Ford, P350

With the above, what I am after is the number of unique models for each manufacturer. Whilst there are 7 fords in total I want to display that there are 3 unique ford models.

I guess a distinct statement is required?
 
Think I have it.

SELECT manufacturer,COUNT(DISTINCT model)
FROM cars
GROUP BY manufacturer
 
Let me try this one next.

Same as above, but only listing those manufacturers with 2 or more models.

Should return only:

Ford 3 models
Nissan 2 models

I tried

SELECT manufacturer,COUNT(DISTINCT model)
FROM cars
GROUP BY manufacturer
HAVING COUNT(DISTINCT model) > 1

but that's not right.

 
That query works for me.
Result:
Ford 3
Nissan 2

-----
ALTER world DROP injustice, ADD peace;
 
OK, how about this next conundrum?

Think of this more like a stock inventory. How do I list those manufacturers who have 2 or more models in stock?

e.g.

Ford, Taurus
Ford, Taurus
Ford, Escort
Ford, Taurus
Ford, P350
Ford, Escort
Mitsubishi, Evo-7
Mitsubishi, Evo-7
Nissan, 350Z
Nissan, 350Z
Nissan, Skyline GT-R
Ford, P350

The report should show

Ford 3 models
Mitsubishi 1 model
Nissan 1 model


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top