Growth ๐ŸŒณ/Practice ๐Ÿ’ป

[Leet Code] 1407. Top Travellers

์ธ” 2023. 10. 20. 17:35

๐Ÿ“ข ๋ณธ ํฌ์ŠคํŒ…์— ํ™œ์šฉ๋˜๋Š” ๊ธฐ๋ณธ ๋ฌธ์ œ ๋ฐ ์ž๋ฃŒ ์ถœ์ฒ˜๋Š”

       ๋ฆฌํŠธ์ฝ”๋“œ Problems, https://leetcode.com/problemset/all/์ž„์„ ๋ฐํž™๋‹ˆ๋‹ค.


โœ”๋ฌธ์ œ

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

 

Top Travellers - LeetCode

Can you solve this real interview question? Top Travellers - Table: Users +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | name | varchar | +---------------+---------+ id is the column with unique values for thi

leetcode.com

Table : Users

Table : Rides

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.


โœ” ํ’€์ด

  ๋ฌธ์ œ ์š”๊ตฌ์‚ฌํ•ญ  

 

์—ฌํ–‰์ž๋ณ„๋กœ ์ด๋™ํ•œ ๊ฑฐ๋ฆฌ๋ฅผ ์ถœ๋ ฅํ•˜๋Š”๋ฐ

์—ฌํ–‰๊ฑฐ๋ฆฌ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•˜๋˜, ๋งŒ์•ฝ ๋‘๋ช… ์ด์ƒ์˜ ์œ ์ €๊ฐ€ ๊ฐ™์€ ๊ฑฐ๋ฆฌ๋ฅผ ์—ฌํ–‰ํ–ˆ๋‹ค๋ฉด ์ด๋ฆ„ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•ด์•ผ ํ•œ๋‹ค.

Users ํ…Œ์ด๋ธ”๊ณผ Rides ํ…Œ์ด๋ธ”์„ ์กฐ์ธํ•  ๋•Œ ์ฃผ์˜ํ•ด์•ผ ํ•  ์ ์€

์กฐ์ธ ์กฐ๊ฑด ์ปฌ๋Ÿผ์ด Users๋Š” id ์ด๊ณ  Rides๋Š” user_id ๋ผ๋Š” ์ ์ด๋‹ค.

๋˜ํ•œ ๊ฒฐ๊ณผ ์ œ์ถœ์ค‘์— ์•„์ด๋””๊ฐ€ ๋‹ค๋ฅธ ๋™๋ช…์ด์ธ์˜ ๊ฒฝ์šฐ๋„ ๊ณ ๋ คํ•ด์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์„ ๋ฐœ๊ฒฌํ–ˆ๋‹ค.

* ๋™๋ช…์ด์ธ ๋ฐ์ดํ„ฐ๋กœ ์ธํ•ด ๊ทธ๋ฃนํ•‘์„ name์œผ๋กœ ํ•  ๊ฒฝ์šฐ, distance ๊ฐ’์ด ํ•œ์‚ฌ๋žŒ์œผ๋กœ ๋ฌถ์—ฌ๋ฒ„๋ฆฌ๋Š” ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฏ€๋กœ

๊ทธ๋ฃน์€ id๊ธฐ์ค€์œผ๋กœ ์ ์šฉํ•ด์•ผ ํ–ˆ๋‹ค.

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

๐Ÿ™‹‍โ™€๏ธ ๋ฌธ์ œ ํ’€์ด์™€ mysql ์ฟผ๋ฆฌ ํšจ์œจ์„ฑ ๋†’์ด๊ธฐ ๋“ฑ ํฌ์ŠคํŒ…์— ๋Œ€ํ•œ ์˜๊ฒฌ ๋ฐ ๊ธฐ์ˆ  ์กฐ์–ธ ๋Œ“๊ธ€ ๋ชจ๋‘ ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค.