https://leetcode.com/problems/trips-and-users/description/
습득한 점:
SUM함수의 새로운 표현법을 알 수 있었다.
SUM(status != 'completed') >>> status 컬럼 중 "completed"가 아닌 데이터의 총 갯수
문제:
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 solution 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". Round Cancellation Rate to two decimal points.
Return the result table in any order.
문제파악:
10/1 ~ 10/3 까지 일자별 여행 취소율을 구하는 문제이다.
취소율은
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.
쿼리 작성 중, 테스트 케이스가 통과 안되는 건이 하나 있었다.
테스트 케이스가 참 이상했다.
저 Input대로 라면, 전체 요청건수는 1개, 그중 취소 요청건수는 1개라 취소율은 100%여야 함에도 불구하고,
Expected에는 아예 값 자체가 보이지 않았다....
그래서 그냥 취소율이 1이 되는 경우는 아예 발생하지 않도록 쿼리를 일부 수정했다.
1. banned 컬럼 값이 No 인 값들의 user_id만 찾을 수 있도록 서브쿼리 작성
2. 만들어 둔 서브 쿼리 자체를 WHERE 조건으로 활용
- clinet_id, driver_id 의 컬럼 값들 중, 서브쿼리로 만들어지는 user_id와 일치하는 조건에 만족하는 SELECT 값을 찾을 수 있도록!
(Trips 테이블의 clinet_id, driver_id //// Users 테이블의 user_id는 foreign key 이다)
3. Between 활용하여, 문제에서 원하는 날짜 지정
4. 날짜 별 취소율을 구하는 것이기 때문에 Group by를 request_at기준으로 지정
5. 취소율을 구할 수 있도록, 완료건이 아닌 취소건의 갯수/ status의 총 갯수 를 구한 뒤, Round 활용해서 소수점 처리
6. 정렬조건은 필요없다고 나와있음
- With 구문을 활용하면 서브쿼리를 2번 적지 않을 수 있다.
- Alias 지정할 때, 중간에 빈칸이 있으면 ' ' 으로 묶어줘야 한다.
풀이:
SELECT request_at AS DAY
, ROUND(SUM(status != 'completed') / COUNT(status),2) AS 'Cancellation Rate'
FROM Trips
WHERE client_id IN (
SELECT users_id
FROM Users
WHERE banned = 'NO'
)
AND driver_id IN (
SELECT users_id
FROM Users
WHERE banned = 'No'
)
AND request_at BETWEEN DATE("2013-10-01") AND DATE ("2013-10-03")
GROUP BY request_at
'sql > easy' 카테고리의 다른 글
180. Consecutive Numbers (0) | 2024.01.15 |
---|---|
Leetcode 185 - Department Top Three Salaries (0) | 2023.09.20 |
프로그래머스 Lv 4 - 보호소에서 중성화한 동물 (Lv 4 문제 마지막) (0) | 2023.08.16 |
프로그래머스 Lv 4 - 식품분류별 가장 비싼 식품의 정보 조회하기 (0) | 2023.08.16 |
프로그래머스 Lv 3 - 조회수가 가장 많은 중고거래 게시판의 첨부파일 조회하기 (0) | 2023.07.19 |