코딩테스트/리트코드

리트코드 database 문제 262. Trips and Users 풀이/쿼리

RyanKwon 2023. 1. 18. 15:28
728x90

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

 

Trips and Users - LeetCode

Trips and Users - Table: Trips +-------------+----------+ | Column Name | Type | +-------------+----------+ | id | int | | client_id | int | | driver_id | int | | city_id | int | | status | enum | | request_at | date | +-------------+----------+ id is the

leetcode.com

Hard로 있길래 풀어봤더니 조인 개념만 정확히 숙지하고 있으면 꽤 쉽게 풀 수 있는 문제이다. 

with tableB as
(select id, client_id, driver_id, city_id, status, request_at
from 
(select id, client_id, driver_id, city_id, status, request_at
from Trips
left join
(select users_id, role
from Users where banned = "No")A --client_id기준/ banned 아닌 테이블과 1차 조인
on client_id = users_id
where users_id is not null)tableA
left join
(select users_id, role
from Users where banned = "No")B --users_id기준/ banned 아닌 테이블에 한번 더 조인
on driver_id = users_id
where users_id is not null and request_at between "2013-10-01" and "2013-10-03") --조건 설정
select request_at as Day, round(sum(case when status not like "co%" then 1 else 0 end)/count(1), 2) as "Cancellation Rate" from tableB
group by request_at --aggregation

요즘들어 코테에 나오는 SQL도 수준이 상당히 높아진 편이라 이정도는 기본으로 해두는게 좋다.

728x90