๐Ÿ’ SQL/Group By

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค][SQL] ์—ฐ๊ฐ„ ํ‰๊ฐ€์ ์ˆ˜์— ํ•ด๋‹นํ•˜๋Š” ํ‰๊ฐ€ ๋“ฑ๊ธ‰ ๋ฐ ์„ฑ๊ณผ๊ธˆ ์กฐํšŒํ•˜๊ธฐ (284528)

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

๋ฌธ์ œ

HR_DEPARTMENT, HR_EMPLOYEES, HR_GRADE ํ…Œ์ด๋ธ”์„ ์ด์šฉํ•ด ์‚ฌ์›๋ณ„ ์„ฑ๊ณผ๊ธˆ ์ •๋ณด๋ฅผ ์กฐํšŒํ•˜๋ คํ•ฉ๋‹ˆ๋‹ค.

ํ‰๊ฐ€ ์ ์ˆ˜๋ณ„ ๋“ฑ๊ธ‰๊ณผ ๋“ฑ๊ธ‰์— ๋”ฐ๋ฅธ ์„ฑ๊ณผ๊ธˆ ์ •๋ณด๊ฐ€ ์•„๋ž˜์™€ ๊ฐ™์„ ๋•Œ,

 

์‚ฌ๋ฒˆ, ์„ฑ๋ช…, ํ‰๊ฐ€ ๋“ฑ๊ธ‰, ์„ฑ๊ณผ๊ธˆ์„ ์กฐํšŒํ•˜๋Š” SQL๋ฌธ์„ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.

ํ‰๊ฐ€๋“ฑ๊ธ‰์˜ ์ปฌ๋Ÿผ๋ช…์€ GRADE๋กœ, ์„ฑ๊ณผ๊ธˆ์˜ ์ปฌ๋Ÿผ๋ช…์€ BONUS๋กœ ํ•ด์ฃผ์„ธ์š”.

๊ฒฐ๊ณผ๋Š” ์‚ฌ๋ฒˆ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•ด์ฃผ์„ธ์š”.

 

---

๊ธฐ์ค€ ์ ์ˆ˜ ํ‰๊ฐ€ ๋“ฑ๊ธ‰ ์„ฑ๊ณผ๊ธˆ(์—ฐ๋ด‰ ๊ธฐ์ค€)

96 ์ด์ƒ S 20%

90 ์ด์ƒ A 15%

80 ์ด์ƒ B 10%

์ด์™ธ C 0%

---

 

ํ’€์ด

select e.EMP_NO, e.EMP_NAME, g.GRADE,
    case when g.GRADE = 'S' then SAL*0.20
    when g.GRADE = 'A' then SAL*0.15
    when g.GRADE = 'B' then SAL*0.10        
    else SAL*0 end as BONUS
from HR_EMPLOYEES e join 
    (
        select EMP_NO,
            case when avg(SCORE) >= 96 then 'S'
            when avg(SCORE) >= 90 then 'A'
            when avg(SCORE) >= 80 then 'B'
            else 'C' end as GRADE
        from HR_GRADE
        group by EMP_NO
    ) g on e.EMP_NO = g.EMP_NO
order by EMP_NO asc

 

์ •๋‹ต ์ฝ”๋“œ ๋จผ์ € ์ฒจ๋ถ€ํ•œ๋‹ค.

์—ญ๋Œ€๊ธ‰์œผ๋กœ ๊ธฐ๋„ค.......

 

์ผ๋‹จ GRADE๋ฅผ ๊ตฌํ•ด์•ผํ•˜๋Š”๋ฐ.. ์™œ์ธ์ง€ ๋ฌธ์ œ์—๋Š” ์„ค๋ช…์ด ๋ˆ„๋ฝ๋˜์–ด์žˆ๋‹ค.

๊ทผ๋ฐ ์„ค๋ช…์€ ๋ˆ„๋ฝ์ธ๋ฐ ์นดํ…Œ๊ณ ๋ฆฌ๋Š” group by๋กœ ๋‚˜๋‰˜์–ด์žˆ๋„ค.. ๋ญ์ง€...

 

์•„๋ฌดํŠผ! HR_GRADE ํ…Œ์ด๋ธ”์—๋Š” ๋ถ„๊ธฐ๋ณ„ ์ ์ˆ˜๋กœ ๋‚˜์™€์žˆ๋‹ค. ์ž์„ธํžˆ๋ณด๋ฉด EMP_NO๊ฐ€ ์ค‘๋ณต์ด๋‹ค

๋”ฐ๋ผ์„œ group by๋กœ ์ง์›๋ณ„ ํ‰๊ท  ์ ์ˆ˜๋ฅผ ๊ตฌํ•œ ๋’ค์—

case when then ์ ˆ์„ ์ด์šฉํ•˜์—ฌ ์•ŒํŒŒ๋ฒณ์„ ๋ถ€์—ฌํ•˜๊ณ  ์ด๋ฅผ GRADE ํ•„๋“œ์— ๋„ฃ์–ด์ฃผ์—ˆ๋‹ค

        select EMP_NO,
            case when avg(SCORE) >= 96 then 'S'
            when avg(SCORE) >= 90 then 'A'
            when avg(SCORE) >= 80 then 'B'
            else 'C' end as GRADE
        from HR_GRADE
        group by EMP_NO

 

์ด์ œ ์ด ํ…Œ์ด๋ธ”๊ณผ(!!) HR_EMPLOYEES ํ…Œ์ด๋ธ”์„ ์กฐ์ธํ•œ๋‹ค.

from HR_EMPLOYEES e join (์œ„ ํ…Œ์ด๋ธ”) g on e.EMP_NO = g.EMP_NO

 

๊ทธ๋ฆฌ๊ณ  GRADE์— ๋”ฐ๋ผ ๋˜ case when then์œผ๋กœ ์„ฑ๊ณผ๊ธˆ์„ ๊ณ„์‚ฐํ•˜๋ฉด ๋

select e.EMP_NO, e.EMP_NAME, g.GRADE,
    case when g.GRADE = 'S' then SAL*0.20
    when g.GRADE = 'A' then SAL*0.15
    when g.GRADE = 'B' then SAL*0.10        
    else SAL*0 end as BONUS
๋ฐ˜์‘ํ˜•