开发者

what is the correct SQL to get "most used query"

开发者 https://www.devze.com 2023-01-03 22:54 出处:网络
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)

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.


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.


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


homework?

try grouping by car_id...

0

精彩评论

暂无评论...
验证码 换一张
取 消