简体   繁体   中英

Finding the decade with highest car mileage

So I have two tables using MySql; Owners and Cars , where an owner has a birthdate and the cars have mileage records. The tables look kinda like this:

Owners:
+-------+--------------+
| Field | Type         |
+-------+--------------+
| id    | varchar(10)  |
| birth | datetime     |
+-------+--------------+

Cars:
+--------------+-------------+
| Field        | Type        |
+--------------+-------------+
| licenceplate | varchar(6)  |
| mileage      | int(11)     |
| owner        | varchar(10) |
+--------------+-------------+

I want a SQL query that provides me with what decade the drivers owning the cars with the highest mileage is. I basically want to group owners born in a certain decade, calculate the average mileage of the cars they are owning, and then present the decade where the average mileage is the highest. I basically want a result like this put into words:

Car Owners born in the 90s are driving their car the most

How do I go about it? I've googled and googled, but can't even find how to select decade. Appreciates any help!

Do you want something like that;

select FLOOR(YEAR(o.birth) / 10 ) * 10 n, max(c.mileage) as maxmileage 
from owners o inner join cars c ON o.id = c.owner
group by n
order by maxmileage desc

Calculate max mileage per decade.

Please excuse any syntax errors in the following as I don't have a MySQL environment.

The logic you require is a little bit unclear, but I'm interpreting your question as meaning "for each birth decade, what was the average mileage driven per driver".

EDIT: as pointed out by @cdaiga, I should include a LIMIT clause to restrict the results to a single row. I've also taken into account @Rainman's answer, and put the extra zero onto the decade in the SELECT which is probably better for presentation and readability.

EDIT 2: I've adjusted the group-by clause to take account of the error referred to in the comments. I wasn't aware that in MySQL, you can reference columns named in the select clause in the group-by clause.

SELECT
    ( (YEAR(birth) DIV 10) * 10 )   AS decade
    ,( SUM(mileage) / COUNT(id) )   AS avg_mileage_per_driver

FROM
    Owners

INNER JOIN
    Cars
    ON Owners.id = Cars.owner

GROUP BY
    decade  -- was:(YEAR(birth) DIV 10)

ORDER BY
    avg_mileage_per_driver DESC

LIMIT 1

I had to combine the two answers that I got to get the average. I got it like this:

SELECT 
    FLOOR(YEAR(o.birth) / 10 ) * 10 AS decade, 
    (SUM(mileage) / COUNT(id)) AS avg_mileage_per_driver 
FROM 
    Owners o 
INNER JOIN 
    Cars c 
ON 
    o.id = c.owner 
GROUP BY 
    decade 
ORDER BY 
    decade 
DESC;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM