Reputation: 2094
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!
Upvotes: 1
Views: 195
Reputation: 960
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
Upvotes: 1
Reputation: 2094
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;
Upvotes: 0
Reputation: 13146
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.
Upvotes: 1