본문 바로가기

LeetCode

1407. Top Travellers

SQL Schema

Pandas Schema

Table: Users

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| name          | varchar |
+---------------+---------+
id is the column with unique values for this table.
name is the name of the user.

 

Table: Rides

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| user_id       | int     |
| distance      | int     |
+---------------+---------+
id is the column with unique values for this table.
user_id is the id of the user who traveled the distance "distance".

 

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.

 

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

 

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

 

COALESCE() 함수

주어진 인수들 중에서 첫 번째로 NULL이 아닌 값을 반환.

여러 개의 인수를 받을 수 있으며, 각 인수를 차례로 검사하면서 첫 번째로 NULL이 아닌 값을 반환. 만약 모든 인수가 NULL이라면, NULL을 반환

 

SELECT COALESCE(NULL, 'A', 'B', 'C');  -- 결과: 'A'
SELECT COALESCE(NULL, NULL, 'B', 'C'); -- 결과: 'B'
SELECT COALESCE(NULL, NULL, NULL);     -- 결과: NULL

 

여행한 거리 합계 계산에서 사용 예시

이 예제에서는 Rides 테이블에 사용자의 여행 거리(distance)가 저장되어 있으며, 사용자가 한 번도 여행하지 않은 경우 그 값이 NULL.

따라서 총 여행 거리를 계산할 때 NULL이 아닌 0을 반환

 

COALESCE() 함수는 NULL 값을 처리하여 다른 값으로 대체할 때 매우 유용