views:

55

answers:

3

i have a table called Rides

id
car_id
distance

i have another table Cars

id
name

i want to run a query that return the most drives per car (on cars that i have rid greater than once)

so the results i am looking for are something like this (to be returned in descending order):

Ford 10
BMW 8
Ferrari 5
Jeep 4

I have:

select car_id, COUNT(car_id) as Cid    
from Rides
group by car_id
order by cid desc

but i can't figure out how to eliminate items that are only 1 ride.

A: 

homework?

try grouping by car_id...

Randy
@Randy - the issue is how to remove items that only show up once
ooo
HAVING does the comparison against the aggregate.
Randy
+3  A: 

To filter derived columns, you can use a HAVING clause.

select car_id, COUNT(car_id) as Cid    
from Rides
group by car_id
having Cid > 1
order by cid desc

OR

having COUNT(car_id) > 1

If your particular brand of SQL doesn't like to use aliases in Having clauses.

Brenton Alker
@Brenton - i am getting an error on this "Incorrect syntax near the keyword 'having'."
ooo
Sorry, had the order of clauses wrong. Having before Order By. (Edited Answer)
Brenton Alker
@Brenton - now getting another error: "Invalid column name 'Cid'", if i changed it to HAVING COUNT(car_id) > 1, it works
ooo
That query works for me. Sounds like your SQL flavour may be case sensitive or doesn't accept aliases in the having clause. I've added an alternate format in case it doesn't accept aliases.
Brenton Alker
+1  A: 

Have a look at the HAVING clause--pun not intended

Scot Hauder