Notice
Recent Posts
Recent Comments
Link
byworld 님의 블로그
멸종위기의 대장균 찾기 본문
sql 문제인 대장균 세대 순회하는 문제를 풀었다. with recursive를 사용해서 트리 구조의 세대를 순회한다.
컨셉은 이렇다. 부모가 null이면 1세대이고, parent_id가 있으면 부모의 세대에 +1씩 하여 자식 세대를 재귀적으로 계산한다.
또한 자식이 없는 세대는
where id not in(select distinct PARENT_ID from ECOLI_DATA where PARENT_ID is not NULL)
처럼 찾을 수 있다. parent_id에 등장한 id는 자식을 가진 부모이다. 추가로, not in 안에 null이 포함되면 sql의 3값 논리 때문에 비교 결과가 unknown이 되어 is not null로 처리했다.
https://school.programmers.co.kr/learn/courses/30/lessons/301651
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
-- 코드를 작성해주세요
with recursive gen as(
select id, parent_id, 1 as generation from ecoli_data where parent_id is null
union all
select e.id, e.parent_id, g.generation+1 as generation
from ecoli_data e join gen g on e.parent_id = g.id
)
select count(*) as COUNT, generation from gen
where id not in(select distinct PARENT_ID from ECOLI_DATA where PARENT_ID is not NULL)
group by generation order by generation;'알고리즘' 카테고리의 다른 글
| 격자 위 최단경로 문제 (0) | 2026.05.09 |
|---|---|
| 프로그래머스 노란불 신호등 + LLM은 바보야 (0) | 2026.05.07 |
| 평행 존재 트릭 (0) | 2026.05.03 |
| 등차함수 알고리즘 트릭 (0) | 2026.05.03 |
| 치킨 쿠폰 숏코딩 (0) | 2026.05.03 |