Tools/- SQL

[SQL] leetcode | 262. Trips and users ์˜ˆ์ œ ํ’€์ด

์Šค์œ„๋ฏผ 2025. 1. 19. 15:04

๋ฌธ์ œ

https://leetcode.com/problems/trips-and-users/

 

์ฝ”๋“œ ๋‹ต์•ˆ

with result as (
select id, client_id, driver_id, status, request_at
from trips t
join (select users_id, banned from users where role = 'client') c
on t.client_id = c.users_id
join (select users_id, banned from users where role = 'driver') d
on t.driver_id = d.users_id
where c.banned = 'No'
 and d.banned = 'No' 
),

request_rate as (
select request_at as Day,
    count(case when status = 'cancelled_by_driver' or status = 'cancelled_by_client' then id else null end) as can_res,
    count(id) as all_res
from result
where request_at between '2013-10-01' and '2013-10-03'
group by request_at
)

select Day, 
    round(can_res / all_res, 2) as 'Cancellation Rate'
from request_rate

^ 25๋ถ„์ด ๊ฑธ๋ฆฐ ๋‚˜์˜ ์ง€์ €๋ถ„ํ•œ ์ฝ”๋“œ .. 

 

select 
    request_at as Day,
    round(sum(if(status = 'completed', 0, 1)) / count(id), 2) as 'Cancellation Rate'
from trips
where client_id in (select users_id from users where role = 'client' and banned = 'No')
and driver_id in (select users_id from users where role = 'driver' and banned = 'No')
and request_at between '2013-10-01' and '2013-10-03'
group by request_at

^ ๋‹ค๋ฅธ ๋ฐ์„œ ๊ฐ€์ ธ์˜จ ๊น”์Œˆํ•œ ์ฝ”๋“œ

์ด๋ž˜์„œ ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ์ฝ”๋“œ๋ฅผ ๊ณต๋ถ€ํ•˜๋Š” ๊ฒŒ ์ค‘์š”ํ•œ ๊ฒƒ ๊ฐ™๋‹ค!

 

ํ•ต์‹ฌ ์š”์ง€

1. ๋ฐ์ดํ„ฐ ๊ฐ€๊ณต์€ ์ง‘๊ณ„๊ฐ€ ์•„๋‹ˆ๋ฉด with์ ˆ์„ ์‚ฌ์šฉํ•œ ์ž„์‹œ ํ…Œ์ด๋ธ”์„ ๋งŒ๋“ค๊ธฐ๋ณด๋‹ค๋Š” ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ์ด์šฉํ•ด๋ณด์ž !

 

b ํ…Œ์ด๋ธ”์— ์žˆ๋Š” ์ •๋ณด๋กœ ์กฐ๊ฑด์„ ๊ฑธ์–ด์„œ a ํ…Œ์ด๋ธ”์— ํ™œ์šฉํ•˜๊ณ  ์‹ถ์œผ๋ฉด

where a.์ปฌ๋Ÿผ in (bํ…Œ์ด๋ธ”์˜ select๋ฌธ)

-> ์ด ๋ฌธ๋ฒ•์„ ์ ๊ทน์ ์œผ๋กœ ์‚ฌ์šฉํ•ด๋ณด์ž.

 

์ž„์‹œํ…Œ์ด๋ธ”์„ ๋งŒ๋“ค ํ•„์š”๋„ ์—†์ด ๋น ๋ฅด๊ฒŒ ์ฝ”๋“œ๋ฅผ ์™„์„ฑ์‹œํ‚ฌ ์ˆ˜ ์žˆ๋‹ค.

๋‚˜๋Š” ๋„ˆ๋ฌด ๋ฌดํ„ฑ๋Œ€๊ณ  with๋กœ ์ž„์‹œํ…Œ์ด๋ธ”์„ ๋จผ์ € ๋งŒ๋“ค๊ณ  ๋ณด๋Š” ๋“ฏ ..;

 

2. if ( ์กฐ๊ฑด, ์ฐธ์ผ ๋•Œ ๊ฐ’, ๊ฑฐ์ง“์ผ ๋•Œ ๊ฐ’)

 

๋‚˜๋Š” sql์—๋„ if๋ฌธ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š”์ง€ ๋ชฐ๋ž๋‹ค ; ์•„๋‹ˆ ๊นŒ๋จน๊ณ  ์žˆ์—ˆ๋‹ค

๊ณ„์† case๋ฌธ๋งŒ ์ฃผ๊ตฌ์žฅ์ฐฝ ๋Œ๋ ธ๋Š”๋ฐ;

 

์กฐ๊ฑด์ด ํ•œ๊ฐœ์ผ ๊ฒฝ์šฐ์—๋Š” if๋ฌธ์„ ์‚ฌ์šฉํ•˜์ž !

 

๋А๋‚€ ์ 

๋ฌธ์ œ๊ฐ€ ๋‚œ์ด๋„๊ฐ€ ๋†’๋‹ค๊ณ 

์ •๋‹ต์ด ๊ตฌ๊ตฌ์ ˆ์ ˆํ•œ ์ฝ”๋“œ์ผ ํ•„์š”๋Š” ์—†๋‹ค

 

์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๊ธฐ ์ „์—

์–ด๋–ป๊ฒŒ ์งค์ง€ ๊ตฌ์กฐ๋ฅผ ๋จธ๋ฆฟ์†์— ํ•œ๋ฒˆ ๊ตฌ์ƒํ•ด์„œ ํ’€๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค.

๊ทผ๋ฐ ์‹œ๊ฐ„ ์••๋ฐ• ๋•Œ๋ฌธ์— ๋งˆ์Œ์ด ๊ธ‰ํ•ด์ ธ์„œ ์‰ฝ์ง€๋Š” ์•Š๋‹ค ใ…œ