
๋ฌธ์
- LeetCode SQL ๋ฌธ์
1204. Last Person to Fit in the Bus / Medium- ๋ฌธ์ ๋ด์ฉ : [๋งํฌ]
๋ด๊ฐ ์์ฑํ Query
with temp_01 as( select turn, person_id, person_name, weight ,sum(weight) over(order by turn) as total_weight from queue ) select distinct last_value(person_name) over(order by total_weight rows between unbounded preceding and unbounded following) as person_name from temp_01 where total_weight <= 1000
window function์ ํตํด ์ ์ฒด ๋ฐ์ดํฐ ๊ธฐ์ค(window) turn ์์๋๋ก weight์ ํฉ์ ๊ตฌํด Total_Weight์ด๋ผ๋ ์ปฌ๋ผ์ ์ถ๋ ฅํด์ค๋ค.
์์ Explanation์ ํ
์ด๋ธ๊ณผ ๊ฐ์ ๋ด์ฉ์ด ์ถ๋ ฅ๋๋ค. ์ด๋ฅผ temp_01๋ก ์ ์ฅํ๋ค.
WHERE์กฐ๊ฑด์ total_weight <= 1000์ธ ์กฐ๊ฑด์ ์ฃผ์ด ๋ฒ์ค ๋ฌด๊ฒ ์ ํ์ ์ด๊ณผํ์ง ์๋ ๋ฐ์ดํฐ๋ง ์ถ๋ ฅ๋๋๋ก ํํฐ๋งํ๋ค.
ํํฐ๋ง ๋ ๋ฐ์ดํฐ์ ๊ฐ์ฅ ๋ง์ง๋ง ๊ฐ์ person_name์ ๊ตฌํด์ค๋ค. ์ด๋ฅผ ์ํด last_valueํจ์๋ฅผ ์ฌ์ฉํ๊ณ , ๋ฐ์ดํฐ ์ ์ฒด ์งํฉ์์ total_weight๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ง์ง๋ง ์งํฉ์ ๊ตฌํด์ผ ํ๋ฏ๋ก, over(order by total_weight rows between unbounded preceding and unbounded following)์ ์ฌ์ฉํด์ค๋ค.
distinct๋ฅผ ํตํด unique ํ ์ฌ๋์ ์ด๋ฆ๋ง ์ถ๋ ฅํด์ค๋ค. (๋ง์ง๋ง ํ์น์ ์ด๋ฆ)
๐๐ window function, last_value()๋ฅผ ์ ์ฉํด๋ณผ ์ ์๋ ๋ฌธ์ ์๋ค.
์ ์ฒด ๋ฐ์ดํฐ์งํฉ(window) ๊ธฐ์ค์ผ๋ก, ๋ง์ง๋ง ํ์น์ ๊ฐ์ด ํ๋ง๋ค ์ถ๋ ฅ๋๋ฏ๋ก,distinct๋ฅผ ํตํด 1๊ฐ์ง ๋ฐ์ดํฐ๋ง ์ถ๋ ฅ๋๋๋ก ํด์ฃผ์๋ค.
