Grokking SQL for Tech Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
20. Bikes Last Time Used
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Problem

Table: Bikes

+-------------+----------+ 
| Column Name | Type     | 
+-------------+----------+ 
| ride_id     | int      | 
| bike_number | text     | 
| start_time  | datetime |
| end_time    | datetime |
+-------------+----------+
ride_id column contains unique values.
Each row contains a ride information that includes ride_id, bike number, start and end time of the ride.

Problem Definition

Write a solution to find the last time when each bike was used.

Return the result table ordered by the bikes that were most recently used.

Example

Image

Output

Image

Try It Yourself

MYSQL
MYSQL

. . . .

Solution

To solve this problem, the approach involves using SQL queries to analyze the Bikes table and determine the last time each bike was used. The table contains information about bike rides, including a unique ride ID, bike number, start time, and end time.

The solution employs the GROUP BY clause along with the Max function to group the data by bike_number and find the maximum (latest) end_time for each bike. This provides the information about the last time each bike was used.

The results are then ordered by the bikes that were most recently used in descending order based on the maximum end time, as specified in the problem statement.

SELECT bike_number, Max(end_time) end_time FROM Bikes GROUP BY bike_number ORDER BY Max(end_time) DESC;

Let's break down the query into more detailed steps:

Step 1: Finding the maximum end time for each bike

We want to find the most recent end time for each bike by grouping the records based on the bike_number and selecting the maximum end_time.

SELECT bike_number, Max(end_time) end_time FROM bikes GROUP BY bike_number

Output After Step 1:

+-------------+---------------------+ | bike_number | end_time | +-------------+---------------------+ | W00576 | 2012-03-28 02:50:00 | | W00300 | 2012-03-25 10:50:00 | | W00455 | 2012-03-26 17:40:00 | +-------------+---------------------+

Step 2: Ordering the result by the most recent end time

We order the result by the maximum end_time in descending order to get the bikes that were most recently used first.

ORDER BY Max(end_time) DESC;

Final Output:

+-------------+---------------------+ | bike_number | end_time | +-------------+---------------------+ | W00576 | 2012-03-28 02:50:00 | | W00455 | 2012-03-26 17:40:00 | | W00300 | 2012-03-25 10:50:00 | +-------------+---------------------+

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible