๐Ÿ’ SQL (Programmers)/Select

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค][SQL] ๋Œ€์žฅ๊ท ๋“ค์˜ ์ž์‹์˜ ์ˆ˜ ๊ตฌํ•˜๊ธฐ (299305)

์„ ๋‹ฌ 2024. 10. 25. 20:05
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

๋Œ€์žฅ๊ท  ๊ฐœ์ฒด์˜ ID(ID)์™€ ์ž์‹์˜ ์ˆ˜(CHILD_COUNT)๋ฅผ ์ถœ๋ ฅํ•˜๋Š” SQL ๋ฌธ์„ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.

์ž์‹์ด ์—†๋‹ค๋ฉด ์ž์‹์˜ ์ˆ˜๋Š” 0์œผ๋กœ ์ถœ๋ ฅํ•ด์ฃผ์„ธ์š”.

์ด๋•Œ ๊ฒฐ๊ณผ๋Š” ๊ฐœ์ฒด์˜ ID ์— ๋Œ€ํ•ด ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•ด์ฃผ์„ธ์š”.

 

ํ’€์ด

select p.ID, ifnull(c.cnt, 0) as CHILD_COUNT
from ECOLI_DATA p left join 
    (
        select PARENT_ID, count(ID) as cnt
        from ECOLI_DATA
        group by PARENT_ID
        having PARENT_ID is not null
    ) c on p.ID = c.PARENT_ID
order by ID
๋ฐ˜์‘ํ˜•