[LeetCode] SQL 50 / ORACLE / 1581. Customer Who Visited But Did Not Make Any Transactions

2024. 1. 6. 16:56Coding/LeetCode-SQL

문제링크

https://leetcode.com/problems/customer-who-visited-but-did-not-make-any-transactions/description/?envType=study-plan-v2&envId=top-sql-50

 

Customer Who Visited but Did Not Make Any Transactions - LeetCode

Can you solve this real interview question? Customer Who Visited but Did Not Make Any Transactions - Table: Visits +-------------+---------+ | Column Name | Type | +-------------+---------+ | visit_id | int | | customer_id | int | +-------------+---------+

leetcode.com

 

문제

 

코드

/* Write your PL/SQL query statement below */
SELECT customer_id, COUNT(visit_id) AS count_no_trans
FROM Visits
WHERE visit_id NOT IN (SELECT visit_id FROM Transactions)
GROUP BY customer_id;

 

1. 'users who visited without making any transactions' 라고 했다. (transactions를 만들지 않고 방문했던 유저)

따라서 WHERE 조건 절에 방문자 id가 Transactions 테이블에 없어야 한다는 조건이 붙어야 했다.

단일 쿼리로는 실현 불가능하다고 생각되었기 때문에 WHERE 절에 서브쿼리를 붙여주었다. 

서브 쿼리 안에는 transactions을 만든 visit_id가 조회하도록 쿼리를 만들어주었다.

그리고 이를 NOT IN 구문 안에 넣어서 해당 쿼리에 조회된 visit_id가 transactions을 만들지 않았다는 조건을 구현해준다.

 

2. 'the number of times they made these types of visits' 라고 했는데, (해당 유저들이 이러한 방문을 만든 횟수)

따라서 visit_id의 횟수를 조회하면 된다. 

그러므로 count()함수 안에 visit_id를 넣어주고 칼럼 명을 포맷에 맞게 작성해주면 된다. 

 

3. Group by 를 왜 넣는지 의문이 드는 사람도 있을텐데, customer_id를 Group by 에 넣지 않으면 각 customer_id가 개별로 조회되어 ' ORA-00937: not a single-group group function ' 오류가 뜬다.