0

I am learning databases and I'm hitting an issue and I want someone to explain it to me. I have a table.

car     | car_id | car_type
________________________________
bmw     |   1    | <bmwcartype1>
bmw     |   1    | <bmwcartype2>
bmw     |   1    | <bmwcartype3>
bmw     |   1    | <bmwcartype4>
mercedes|   2    | <mercedescartype1>
mercedes|   2    | <mercedescartype2>
mercedes|   2    | <mercedescartype3>
lexus   |   3    | <lexuscartype1>
lexus   |   3    | <lexuscartype2>
lexus   |   3    | <lexuscartype3>
lexus   |   3    | <lexuscartype4>
lexus   |   3    | <lexuscartype5>

I want to display for example the car and the number of cartypes. I'm not sure how to explain this but on the table above I only managed to get the first row.

SELECT car, COUNT(car) AS number_of_cars FROM cars WHERE car_id = 1

This is displaying the first row like:

car | number_of_cars
bmw |   4

And I want the following rows to be:

car      | number_of_cars
bmw      | 4
mercedes | 3
lexus    | 5

How can I do that?

2
  • 1
    Instead of the where clause, add group by car. Commented May 14, 2014 at 23:19
  • @GordonLinoff That was exactly what I was looking for, Gordon. Can you post your answer properly so I can mark it as solved and rate you? Commented May 14, 2014 at 23:20

1 Answer 1

1

You have an aggregation query that returns one row. Just as a note, this query works in MySQL but would fail in most databases. The column car is not in a group by. Even though you are choosing only one value, SQL engines don't usually allow this (MySQL is an exception).

The query that you want is:

SELECT car, COUNT(car) AS number_of_cars
FROM cars
group by car;

Note that car appear both in the select and group by. Although you could have car_id in the group by. this is bad form. Try to be sure that the unaggregated columns in the select are always in the group by -- at least until you really understand what you are doing with SQL.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.