๐ป ๋ฌธ์ ์ฃผ์ : Customer Who Visited but Did Not Make Any Transactions - LeetCode
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 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 table sorted in any order
- ๋์ค๊ตํต์ ์ด์ฉํ์ง ์์ ์ ์ ๋ค์ ID, ์ด๋ฐ ์ ํ์ ๋ฐฉ๋ฌธ ํ์๋ฅผ ์ถ๋ ฅํ์์ค. ์ถ๋ ฅ ์์๋ ์๊ด ์์ต๋๋ค.

๐ป ์ฝ๋ ๋ฐ ํ์ด - 1) subquery ํ์ฉ
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
๐ป ์ฝ๋ ๋ฐ ํ์ด - 2) join ํ์ฉ
select v.customer_id, count(v.visit_id) as count_no_trans
from Visits v
left join Transactions t on v.visit_id = t.visit_id
where isnull(t.transaction_id) = 1
group by v.customer_id
๐ป Beats
1) ์๋ธ์ฟผ๋ฆฌ ํ์ฉ ์ฟผ๋ฆฌ์ ๊ฒฝ์ฐ : beats 35.49%
2) ์กฐ์ธ ํ ์ฉ ์ฟผ๋ฆฌ์ ๊ฒฝ์ฐ : beats 59.67%
์์ฒ๋ผ ๋ฌด์์ ํ์ฉํ๋์ง์ ๋ฐ๋ผ beats ์ฐจ์ด๊ฐ ๋ฐ์ํ๋ค. ์ด์ฒ๋ผ ์๋ธ์ฟผ๋ฆฌ๋ ์กฐ์ธ์ ๋นํด beats๊ฐ ์ ๋์ฌ ๋๊ฐ ๋ฐ์ํ๋๋ฐ, ์ด๋ '์ฟผ๋ฆฌ์ ๋ฐ๋ณต์ผ๋ก ์ธํ ์ํ๋ ฅ' ๋๋ฌธ์ด๋ค.
where visit_id not in (select visit_id from Transactions)
์ ๊ตฌ๋ฌธ์ ๋ณด๋ฉด ํธ๋์ญ์ ์ ์ด์ฉํ์ง ์๋ id๋ฅผ ์ฐพ๊ธฐ ์ํด visit_id ํ๋๋น Transactions ํ ์ด๋ธ์ ์๋ visit_id ๋ชฉ๋ก์ ์ดํด๋ด์ผ ํ๋ค.
left join Transactions t on v.visit_id = t.visit_id
์ด์ ๋นํด ์กฐ์ธ์ ๊ฒฝ์ฐ, visit_id๊ฐ ์ผ์นํ๋ ๋ฐ์ดํฐ์ ํํด Visits ํ ์ด๋ธ์ Transactions ํ ์ด๋ธ ๋ฐ์ดํฐ๋ฅผ ํฉ์น๊ณ , ์ด ํ์๋ ๋งค๋ฒ visit_id๋ฅผ ๋น๊ตํ ํ์ ์์ด where ๊ตฌ๋ฌธ์ ํตํด ๋ฐ๋ก ์ํ๋ ์กฐ๊ฑด์ ๊ฑธ๋ฉด ๋๋ค. ์ฆ, '๋ฐ๋ณต'์ด ์ฌ๋ผ์ง ์ ์ด๋ค.
๊ทธ๋ ๋ค๋ฉด ์๋ธ์ฟผ๋ฆฌ๋ณด๋ค ์กฐ์ธ์ด ์๋ ๋ถ๋ถ์ ์์ด ๋ ์ฐ์ํ๋ค๋ ๊ฒ์ธ๋ฐ ์ ์๋ธ์ฟผ๋ฆฌ ๋ฅผ ์ด์ฉํ๋ ๊ฒ์ผ๊น? ์ด๋ ์กฐ์ธ์ ์ฌ์ฉํ ์ ์๋ ๊ฒฝ์ฐ๊ฐ ์๊ธฐ ๋๋ฌธ์ด๋ค.
-----------(1) Group by ํ์ฉํ subqurey๊ฐ from ์ ์ ์์ ๋
(2) ์ง๊ณํ ๊ฐ์ ๋ฆฌํดํ๋ ์๋ธ์ฟผ๋ฆฌ๊ฐ where ์ ์ ์์ ๋
(3) ์๋ธ์ฟผ๋ฆฌ๊ฐ All ์ฐ์ฐ์ ์์ ์์ ๋
์ ์ผ์ด์ค์ ๋ํ ์์ธ ์ค๋ช ์ ์ถํ ๋ค๋ฃจ๋๋ก ํ์.
'SQL > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode][SQL50] #10. Average Time of Process per Machine (0) | 2023.11.08 |
---|---|
[LeetCode][SQL50] #9. Rising Temperature (0) | 2023.11.08 |
[LeetCode][SQL50] #7. Product Sales Analysis I (0) | 2023.11.07 |
[LeetCode][SQL50] #6. Replace Employee ID With The Unique Identifier (0) | 2023.11.07 |
[LeetCode][SQL50] #5. Invalid Tweets (0) | 2023.11.06 |