Snoopy [리트코드/SQL] 28. Top Travellers (1407)
코딩테스트/리트코드 SQL

[리트코드/SQL] 28. Top Travellers (1407)

Sooyoon Jeong 2022. 12. 23.

🤔 문제 분석

1) Return the result table ordered by travelled_distance in descending order,

2) if two or more users traveled the same distance, order them by their name in ascending order.

 

💡 풀이

SELECT U.name, if(R.distance IS NULL, 0, R.distance)AS travelled_distance
FROM Users AS U
    LEFT JOIN (SELECT user_id, sum(distance) AS distance
          FROM Rides
          GROUP BY user_id)
    AS R ON U.id = R.user_id
ORDER BY travelled_distance DESC, name

댓글