๐ข ๋ณธ ํฌ์คํ ์ ํ์ฉ๋๋ ๊ธฐ๋ณธ ๋ฌธ์ ๋ฐ ์๋ฃ ์ถ์ฒ๋
๋ฆฌํธ์ฝ๋ Problems, https://leetcode.com/problemset/all/์์ ๋ฐํ๋๋ค.
โ ๋ฌธ์
https://leetcode.com/problems/human-traffic-of-stadium/description/
Human Traffic of Stadium - LeetCode
Can you solve this real interview question? Human Traffic of Stadium - Table: Stadium +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | visit_date | date | | people | int | +---------------+---------+ visit_date
leetcode.com
Table : Stadium
Write an SQL query to display the records with three or more rows with consecutive id's, and the number of people is greater than or equal to 100 for each.
Return the result table ordered by visit_date in ascending order.
The query result format is in the following example.
โ ํ์ด
๋ฌธ์ ์๊ตฌ์ฌํญ
์์ด๋๊ฐ 3๊ฐ ์ด์ ์ฐ์์ด๋ฉด์ ๊ฐ ๋ฐฉ๋ฌธ์ ์๊ฐ 100 ์ด์์ธ ํ์ ์ถ๋ ฅํ์์ค.
์ฆ, ์ ์๋ ํ์ ๋ฐฉ๋ฌธ์ ์๊ฐ 100 ์ด์์ธ ํ์ ์ถ๋ ฅํ์์ค.์ด์ ํ, ๋ค์ํ์ ์ถ๋ ฅํ ์ ์๋ LEAD(), LAG() ํจ์๋ฅผ ์ด์ฉํ ์ ์๋ค.๋จ, ์๋ ํ ์ด๋ธ์ ๋ชจ๋ ํ์ด ๊ธฐ์คํ์ด ๋ ์ ์์ผ๋ฏ๋ก ๊ธฐ์คํ ์ 2ํ, ๋ค2ํ์ ๋ชจ๋ ๋ฐ์ ธ์ฃผ์ด์ผ ํ๋ค.
๋ฌธ์ ์กฐ๊ฑด์ ์ถฉ์กฑํ๋ ๊ฒฝ์ฐ์ ์๋ ์ด ์ธ๊ฐ์ง๋ก ๋๋๋ค.
(id์ปฌ๋ผ ์ค๋ฆ์ฐจ์ ๊ธฐ์ค)
๊ธฐ์คํ-2 people๊ฐ | ๊ธฐ์คํ-1 people๊ฐ | ๊ธฐ์คํ people๊ฐ | ๊ธฐ์คํ+1 people๊ฐ | ๊ธฐ์คํ+2 people๊ฐ |
A | B | C | D | E |
โ case1 | C์ A, B๊ฐ ๊ฐ๊ฐ 100๋ช ์ด์์ธ ๊ฒฝ์ฐ
โ case2 | C์ B, D๊ฐ ๊ฐ๊ฐ 100๋ช ์ด์์ธ ๊ฒฝ์ฐ
โ case3 | C์ D, E๊ฐ ๊ฐ๊ฐ 100๋ช ์ด์์ธ ๊ฒฝ์ฐ
case๋ ์๋์ ๊ฐ์ด WHERE์ ์ ์กฐ๊ฑด์ผ๋ก ๋ฃ์ด์ค ์ ์๋ค.
WITH T1 AS (SELECT id, visit_date, people
,lead(people, 1) OVER (order by id) AS da1_people
,lead(people, 2) OVER (order by id) AS da2_people
,lag(people, 1) OVER (order by id) AS db1_people
,lag(people, 2) OVER (order by id) AS db2_people
FROM stadium)
SELECT id, visit_date, people
FROM T1
WHERE T1.people >= 100 AND ((T1.da1_people >= 100 AND T1.da2_people >= 100)
OR (T1.db1_people >= 100 AND T1.da1_people >= 100)
OR (T1.db1_people >= 100 AND T1.db2_people >= 100))
โ ๊ฐ์ธํ๊ณ
์ฒ์์ LEADํจ์๋ง ์ฌ์ฉํด์ ๋ง์ง๋ง id 2ํ์ด people๊ฐ์ด 100 ์ด์ ์์๋ ์ถ๋ ฅ๋์ง ์๋ ๊ฒ์์ ๋งํ๋ค.
์๋ 2ํ์ ๋ฐ๋ก ์ถ๋ ฅํ ๋ฐฉ๋ฒ๋ง ๊ณ ๋ฏผํ๋ค๊ฐ ๊ธฐ์คํ ์2๊ฐ ๋ค2๊ฐ๊น์ง ์ปฌ๋ผ์ผ๋ก ๋ง๋ค์ด์ฃผ๊ณ ๋ณด๋ ์กฐ๊ฑด์ ํด๋นํ๋ ํ์ ๋๋ฝ์์ด ์ถ๋ ฅํ ์ ์์๋ค.
WHERE ์กฐ๊ฑด์ ๋ ๊ธฐ์กด์ AND, OR๋ง ์ฌ์ฉํ๋ค๊ฐ ๊ฒฝ์ฐ์ ์๋ก ๋๋๋ ์กฐ๊ฑด์ ์ ์ฉํด๋ณผ ์ ์๋ ๋ฌธ์ ์๋ค.
๋ฌธ์ ์์ ํ๋ฒ ์ฌ์ฉํ ๋ฌธ๋ฒ์ ์ ๊ธฐ์ตํด๋ ๊ฒ!
'Growth ๐ณ > Practice ๐ป' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] 608. Tree Node (0) | 2023.05.16 |
---|---|
[LeetCode] 602. Friend Requests II: Who Has the Most Friends (0) | 2023.05.12 |
[LeetCode] 577. Employee Bonus (0) | 2023.05.10 |
[LeetCode] 585. Investments in 2016 (0) | 2023.05.09 |
[LeetCode] 570. Managers with at Least 5 Direct Reports (0) | 2023.04.24 |