본문 바로가기
취준/코팅 테스트

[LeetCode] 1407. Top Travellers

by 소복소복뚜벅뚜벅 2024. 3. 12.

문제 

https://leetcode.com/problems/top-travellers/description/

Write a solution to report the distance traveled by each user.

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

 

 

문제 해답 

SELECT u.name AS name
	, IFNULL(SUM(r.distance),0) AS travelled_distance 
FROM Users AS u 
LEFT JOIN Rides AS R on u.id = r.user_id 
GROUP BY r.user_id 
ORDER BY travelled_distance DESC, name ASC

 

오답노트 

1. User tabel에는 있고, Rides table의 유저는 없는 상황을 살피지 않은 것 

2. Null 값을 0으로 바꾼 IFNULL 함수를 까먹은 것 

3. GROUP BY 할때 name이 아닌 user_id로 해야 했다는 것. 중복된 이름이 있기 때문에, 고유한 id를 사용해야 했다는 것.