728x90
join 세번째 문제
⬆️ 문제 전문 링크는 여기
Table: Visits
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| visit_id | int |
| customer_id | int |
+-------------+---------+
visit_id is the column with unique values for this table.
This table contains information about the customers who visited the mall.
Table: Transactions
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| transaction_id | int |
| visit_id | int |
| amount | int |
+----------------+---------+
transaction_id is column with unique values for this table.
This table contains information about the transactions made during the visit_id.
Write a solution to find the IDs of the users who visited without making any transactions and the number of times they made these types of visits.
Return the result table sorted in any order.
The result format is in the following example.
Example 1:
Input:
Visits
+----------+-------------+
| visit_id | customer_id |
+----------+-------------+
| 1 | 23 |
| 2 | 9 |
| 4 | 30 |
| 5 | 54 |
| 6 | 96 |
| 7 | 54 |
| 8 | 54 |
+----------+-------------+
Transactions
+----------------+----------+--------+
| transaction_id | visit_id | amount |
+----------------+----------+--------+
| 2 | 5 | 310 |
| 3 | 5 | 300 |
| 9 | 5 | 200 |
| 12 | 1 | 910 |
| 13 | 2 | 970 |
+----------------+----------+--------+
Output:
+-------------+----------------+
| customer_id | count_no_trans |
+-------------+----------------+
| 54 | 2 |
| 30 | 1 |
| 96 | 1 |
+-------------+----------------+
Explanation:
Customer with id = 23 visited the mall once and made one transaction during the visit with id = 12.
Customer with id = 9 visited the mall once and made one transaction during the visit with id = 13.
Customer with id = 30 visited the mall once and did not make any transactions.
Customer with id = 54 visited the mall three times. During 2 visits they did not make any transactions, and during one visit they made 3 transactions.
Customer with id = 96 visited the mall once and did not make any transactions.
As we can see, users with IDs 30 and 96 visited the mall one time without making any transactions. Also, user 54 visited the mall twice and did not make any transactions.
문제가 굉장히 길지만 요약하자면 다음과 같다.
[방문했으나 거래를 하지 않은 고객 선별]
방문 테이블 / 거래 테이블이 있고
우리는 방문 테이블에서 고객을 뽑을건데, 거래를 하지 않은 고객을 방문만 하고 거래 하지 않은 횟수와 함께 뽑을 것이다.
밴다이어그램으로 표현하자면 우리는 파란영역의 값이 필요하다.
따라서 left outer join을 사용할 것이며
그의 코드는 다음과 같다.
select v.customer_id, sum(1) as count_no_trans
from Visits v left outer join Transactions t on v.visit_id = t.visit_id
where t.visit_id is null
group by v.customer_id;
728x90
반응형
'알고리즘' 카테고리의 다른 글
[SQL] 197. Rising Temperature (EASY) (0) | 2025.01.20 |
---|---|
[SQL] 1068. Product Sales Analysis I (Easy) (0) | 2024.12.31 |
[SQL] 1378. Replace Employee ID With The Unique Identifier (Easy) (0) | 2024.12.31 |
[SQL] 1683. Invalid Tweets (Easy) (1) | 2024.12.26 |
[SQL] 1148. Article Views I (Easy) (0) | 2024.12.26 |