Tools/- SQL

[SQL] solvesql | ์Šคํ…Œ๋””์…€๋Ÿฌ ์ž‘๊ฐ€ ์ฐพ๊ธฐ

์Šค์œ„๋ฏผ 2025. 2. 9. 17:46

๋ฌธ์ œ

https://solvesql.com/problems/find-steadyseller-writers/

 

https://solvesql.com/problems/find-steadyseller-writers/

 

solvesql.com

 

์ฝ”๋“œ ๋‹ต์•ˆ

ํƒ€ ๋ธ”๋กœ๊ทธ ํ’€์ด

with fictions as (
  select DISTINCT
    author,
    year
  from 
    books
  where
    genre = "Fiction"
  order by 1,2
 )

select author, max(year) as year, count(*) as depth
from
 (select *, year - row_number() over () as grp_num
 from fictions) as t
group by author, grp_num
having count(*) >= 5

 

๋ฌธ์ œ ํฌ์ธํŠธ

1. ์žฅ๋ฅด๊ฐ€ "Fiction"์ธ ๋ฐ์ดํ„ฐ๋ฅผ ํ•„ํ„ฐ๋ง

 

2. ๋…„๋„์—์„œ row_number๋ฅผ ๋นผ์„œ ์—ฐ์†์ ์ธ ๋…„๋„๋ฅผ ๊ตฌํ•œ๋‹ค

๋…„๋„์—์„œ row_number๋ฅผ ๋บ์„ ๋•Œ ์—ฐ์†์ ์ธ ๋…„๋„์ด๋ฉด ๊ฐ™์€ ์ˆซ์ž (grp_num)์„ ๋ถ€์—ฌ๋ฐ›๊ฒŒ ๋œ๋‹ค.

grp_num์„ ๊ธฐ์ค€์œผ๋กœ ๋‹ค์‹œ ๊ทธ๋ฃนํ•‘ ํ›„ count(*)์„ ํ•˜๋ฉด ์—ฐ์†์ ์ธ ํ–‰์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.

 

3. ์—ฐ์†์ ์ธ ํ–‰์ด 5๊ฐœ ์ด์ƒ์ธ grp_num์—์„œ ๊ฐ€์žฅ ์ตœ์‹  ๋…„๋„๋ฅผ ๊ตฌํ•œ๋‹ค.

 

๋А๋‚€ ์ 

์˜ˆ์ „์—๋„ ๊ฐ™์€ ๋ฐฉ๋ฒ•์œผ๋กœ ์—ฐ์†์ ์ธ ์ˆซ์ž๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ๊ฐ€ ๋‚˜์™”์—ˆ๋Š”๋ฐ

์จ๋จน์„ ์ƒ๊ฐ์„ ๋ชปํ–ˆ๋‹ค ใ… 

๋ณต์Šต์ค‘์š” !