SQL Interview Questions – Top Travelers

Spread the love

Problem Description –

Write an SQL query to report the distance traveled by each user.

Return the result table ordered by traveled/_distance in descending order, if two or more users traveled the same distance, order them by their name in ascending order.

The query result format is in the following example.

Difficulty Level – Easy

Problem Link – Top Travelers

Solution –

SELECT
    u.name,
    IFNULL(SUM(distance),0) as travelled_distance
FROM Users as u LEFT JOIN Rides as r
ON r.user_id = u.id
GROUP BY 1
ORDER BY 2 DESC, 1

Rating: 1 out of 5.

Leave a Reply