๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
SQL/LeetCode

[LeetCode] (์„œ๋ธŒ์ฟผ๋ฆฌ, ์กฐ์ธ ์†๋„) #8. Customer Who Visited but Did Not Make Any Transactions

by ์ด๋ฎด 2023. 11. 8.
728x90

๐Ÿ’ป ๋ฌธ์ œ ์ฃผ์†Œ : 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, ์ด๋Ÿฐ ์œ ํ˜•์˜ ๋ฐฉ๋ฌธ ํšŸ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜์‹œ์˜ค. ์ถœ๋ ฅ ์ˆœ์„œ๋Š” ์ƒ๊ด€ ์—†์Šต๋‹ˆ๋‹ค.

Input๊ณผ Output ์˜ˆ์‹œ

 

๐Ÿ’ป ์ฝ”๋“œ ๋ฐ ํ’€์ด - 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 ์—ฐ์‚ฐ์ž ์•ˆ์— ์žˆ์„ ๋•Œ

 

์œ„ ์ผ€์ด์Šค์— ๋Œ€ํ•œ ์ƒ์„ธ ์„ค๋ช…์€ ์ถ”ํ›„ ๋‹ค๋ฃจ๋„๋ก ํ•˜์ž.

 
728x90
๋ฐ˜์‘ํ˜•