Growth ๐ŸŒณ/Practice ๐Ÿ’ป

[LeetCode] 262. Trips and Users

์ธ” 2022. 8. 26. 15:37

 

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

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


โ–  ๋ฌธ์ œ

https://leetcode.com/problems/department-highest-salary/

 

Department Highest Salary - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

โ–  ํ’€์ด

The cancellation rate is computed by dividing the number of canceled (by client or driver) requests

with unbanned users by the total number of requests with unbanned users on that day.

 

Write a SQL query to find the cancellation rate of requests with unbanned users (both client and driver must not be banned) each day between "2013-10-01" and "2013-10-03".

> 2013.10.01 ๋ถ€ํ„ฐ 2013.10.03 ๊นŒ์ง€ ์ทจ์†Œ์œจ์„ ์ฐพ๋Š” ์ฟผ๋ฆฌ๋ฅผ ๋งŒ๋“ ๋‹ค.

   ๋‹จ, ๊ณ ๊ฐ๊ณผ ์šด์ „์ž๊ฐ€ ๋ชจ๋‘ ๊ธˆ์ง€ ์ƒํƒœ์—ฌ์„œ๋Š” ์•ˆ๋œ๋‹ค.

 

Round Cancellation Rate to two decimal points. Return the result table in any order.

> ์ทจ์†Œ์œจ์€ ์†Œ์ˆ˜์  ๋‘˜์งธ์ž๋ฆฌ๊นŒ์ง€ ๋ฐ˜์˜ฌ๋ฆผํ•˜๊ณ  ๊ฒฐ๊ณผ ์ˆœ์„œ๋Š” ์ž„์˜๋กœ ๋ฐ˜ํ™˜

SELECT T2.day,
       Round(avg(T2.status like '%cancel%'), 2) `Cancellation Rate`
 FROM (
        SELECT T.request_at Day,
               T.status status
         FROM Trips T

         LEFT JOIN Users U
         ON (T.client_id = U.users_id)&(U.role = 'client')

         LEFT JOIN Users U2
         ON (T.driver_id = U2.users_id)&(U2.role='driver')

        WHERE T.request_at BETWEEN '2013-10-01' AND '2013-10-03'
        AND U.banned = 'No'
        AND U2.banned = 'No') T2
GROUP BY T2.day
;

ํ…Œ์ด๋ธ”์€ ์˜ˆ์•ฝํ˜„ํ™ฉ ํ…Œ์ด๋ธ”์ธ Trips

                ์‚ฌ์šฉ์ž ์ •๋ณด ํ…Œ์ด๋ธ”์ธ Users

 

FROM ์ ˆ ์ฝ”๋“œ ํ’€์ด

Trips ํ…Œ์ด๋ธ”์— ์‚ฌ์šฉ์ž(๊ณ ๊ฐ, ์šด์ „์ž)์— ๋Œ€ํ•œ ๊ธˆ์ง€ ์ •๋ณด๋ฅผ ๋„ฃ์–ด์ค˜์•ผํ•ด์„œ

Trips ํ…Œ์ด๋ธ” ๊ธฐ์ค€  user ํ…Œ์ด๋ธ”์„ ๋‘๋ฒˆ left join ํ•˜๋ฉด์„œ 

์ฒซ๋ฒˆ์งธ ์กฐ์ธ ์กฐ๊ฑด์€ ์‚ฌ์šฉ์ž์ค‘ ๊ณ ๊ฐid, ๊ทธ๋ฆฌ๊ณ  role์ด ๊ณ ๊ฐ

๋‘๋ฒˆ์จฐ ์กฐ์ธ ์กฐ๊ฑด์€ ์‚ฌ์šฉ์ž์ค‘ ์šด์ „์žid ๊ทธ๋ฆฌ๊ณ  role์ด ์šด์ „์ž

 

SELECT์ ˆ ํ’€์ด

์ด ์กฐ์ธ ํ…Œ์ด๋ธ”์—์„œ ์˜ˆ์•ฝ ๋‚ ์งœ์™€, ์˜ˆ์•ฝ ์ƒํƒœ๋ฅผ ์ถœ๋ ฅํ•˜๋Š”๋ฐ

์กฐ๊ฑด์€ 1) ์š”์ฒญ์ผ์ž 2013-10-01 ~ 2013-10-03 ์œผ๋กœ ์ œํ•œ > Between '2013-10-01' and '2013-10-03'

             2) '์‚ฌ์šฉ์ž(๊ณ ๊ฐ, ์šด์ „์ž)๋Š” ๋ชจ๋‘ ๊ธˆ์ง€์ƒํƒœ๊ฐ€ ์•„๋‹ˆ์—ฌ์•ผ ํ•œ๋‹ค '์„ WHERE์ ˆ์— ๋„ฃ์–ด์ค€ ๊ฒฐ๊ณผ T2์—์„œ

 

์š”์ฒญ์ผ์ž(request_at)์™€ ์ผ์ž๋ณ„ ์ทจ์†Œ์œจ(๋ฐ˜์˜ฌ๋ฆผํ•ด์„œ ์†Œ์ˆ˜ ๋‘˜์งธ์ž๋ฆฌ๊นŒ์ง€)์„ ๊ตฌํ•œ๋‹ค.

์ผ์ž๋ณ„๋กœ ๊ตฌํ•˜๊ธฐ ์œ„ํ•ด ์š”์ฒญ์ผ์ž๋ณ„ ๊ทธ๋ฃนํ•‘ > group by T2.day

์ทจ์†Œ์œจ์˜ ํ‰๊ท  > agv(T2.status like '%cancel%') 

์ทจ์†Œ์œจ ํ‘œ๊ธฐ๋Š” ์†Œ์ˆ˜์  ๋‘˜์งธ์ž๋ฆฌ๊นŒ์ง€ > round(avg(T2.status like '%cancel%'), 2)