|
| 1 | +/* |
| 2 | +Question 3601. Find Drivers with Improved Fuel Efficiency |
| 3 | +Link: https://leetcode.com/problems/find-drivers-with-improved-fuel-efficiency/description/?envType=problem-list-v2&envId=database |
| 4 | +
|
| 5 | +Table: drivers |
| 6 | +
|
| 7 | ++-------------+---------+ |
| 8 | +| Column Name | Type | |
| 9 | ++-------------+---------+ |
| 10 | +| driver_id | int | |
| 11 | +| driver_name | varchar | |
| 12 | ++-------------+---------+ |
| 13 | +driver_id is the unique identifier for this table. |
| 14 | +Each row contains information about a driver. |
| 15 | +Table: trips |
| 16 | +
|
| 17 | ++---------------+---------+ |
| 18 | +| Column Name | Type | |
| 19 | ++---------------+---------+ |
| 20 | +| trip_id | int | |
| 21 | +| driver_id | int | |
| 22 | +| trip_date | date | |
| 23 | +| distance_km | decimal | |
| 24 | +| fuel_consumed | decimal | |
| 25 | ++---------------+---------+ |
| 26 | +trip_id is the unique identifier for this table. |
| 27 | +Each row represents a trip made by a driver, including the distance traveled and fuel consumed for that trip. |
| 28 | +Write a solution to find drivers whose fuel efficiency has improved by comparing their average fuel efficiency in the first half of the year with the second half of the year. |
| 29 | +
|
| 30 | +Calculate fuel efficiency as distance_km / fuel_consumed for each trip |
| 31 | +First half: January to June, Second half: July to December |
| 32 | +Only include drivers who have trips in both halves of the year |
| 33 | +Calculate the efficiency improvement as (second_half_avg - first_half_avg) |
| 34 | +Round all results to 2 decimal places |
| 35 | +Return the result table ordered by efficiency improvement in descending order, then by driver name in ascending order. |
| 36 | +*/ |
| 37 | + |
| 38 | +WITH first_avg AS ( |
| 39 | + SELECT |
| 40 | + driver_id, |
| 41 | + AVG(distance_km::numeric / fuel_consumed) AS first_half_avg |
| 42 | + FROM trips |
| 43 | + WHERE trip_date < '2023-07-01' |
| 44 | + GROUP BY driver_id |
| 45 | +), |
| 46 | + |
| 47 | +second_avg AS ( |
| 48 | + SELECT |
| 49 | + driver_id, |
| 50 | + AVG(distance_km::numeric / fuel_consumed) AS second_half_avg |
| 51 | + FROM trips |
| 52 | + WHERE trip_date >= '2023-07-01' |
| 53 | + GROUP BY driver_id |
| 54 | +) |
| 55 | + |
| 56 | +SELECT |
| 57 | + d.driver_id, |
| 58 | + d.driver_name, |
| 59 | + ROUND(fa.first_half_avg, 2) AS first_half_avg, |
| 60 | + ROUND(sa.second_half_avg, 2) AS second_half_avg, |
| 61 | + ROUND((sa.second_half_avg - fa.first_half_avg), 2) AS efficiency_improvement |
| 62 | +FROM first_avg AS fa |
| 63 | +INNER JOIN |
| 64 | + second_avg AS sa |
| 65 | + ON fa.driver_id = sa.driver_id |
| 66 | +LEFT JOIN |
| 67 | + drivers AS d |
| 68 | + ON fa.driver_id = d.driver_id |
| 69 | +WHERE (sa.second_half_avg - fa.first_half_avg) > 0 |
| 70 | +ORDER BY efficiency_improvement DESC, d.driver_name ASC |
0 commit comments