๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
ORACLE/SQL

[Oracle] DECODE ํ•จ์ˆ˜ ์‚ฌ์šฉ ์ฟผ๋ฆฌ ๊ฒฐ๊ณผ ๊ฐ€๋กœ๋กœ ๋ณด๊ธฐ :: ๋งˆ์ด์ž๋ชฝ

by ๐ŸŒปโ™š 2020. 3. 20.

DECODE ํ•จ์ˆ˜

DECODE ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ฟผ๋ฆฌ๋‚ด์˜ ์กฐ๊ฑด๋ฌธ ์ฒ˜๋Ÿผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ฒซ๋ฒˆ์งธ ์ธ์ž๋กœ ํ™•์ธํ•  ๋Œ€์ƒ์„ ๋„ฃ์–ด์ฃผ๊ณ  2๋ฒˆ์งธ ์ธ์ž์— ํ™•์ธํ•  ๋Œ€์ƒ์˜ ์˜ˆ์ธก ๊ฐ’์ด ์žˆ์œผ๋ฉด 3๋ฒˆ์งธ ์ธ์ž๋ฅผ ์—†์œผ๋ฉด 4๋ฒˆ์งธ ์ธ์ž์˜ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ด์ค๋‹ˆ๋‹ค.

 

CASE ํ‘œํ˜„์‹๊ณผ๋Š” ๋‹ค๋ฅด๊ฒŒ ๋ฒ”์œ„์‹์˜ ์กฐ๊ฑด์„ ๋„ฃ์„์ˆ˜ ์—†๊ณ  2๋ฒˆ์งธ ์ธ์ž๊ฐ€ ์žˆ๋Š”์ง€ ์—†๋Š”์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. Oracle Scott ๊ณ„์ •์œผ๋กœ DECODE ํ•จ์ˆ˜ ์‚ฌ์šฉ ์˜ˆ์‹œ๋ฅผ ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

์„ธ๋กœ๊ฒฐ๊ณผ๋ฅผ ๊ฐ€๋กœ๋กœ

1
2
3
4
5
6
SELECT
    DEPARTMENT_ID
    ,SUM(SALARY)
FROM EMPLOYEES
WHERE DEPARTMENT_ID <=30
GROUP BY DEPARTMENT_ID;

๋ถ€์„œ๋ฒˆํ˜ธ๊ฐ€ 30 ์ดํ•˜์ธ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถ€์„œ๋กœ GROUP BY ํ–ˆ์Šต๋‹ˆ๋‹ค. ์„ธ๋กœํ˜•ํƒœ๋กœ ๋˜์–ด์žˆ๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€๋กœ๋กœ ๋ณ€ํ™˜์‹œ์ผœ์ฃผ๋Š” ์˜ˆ์ œ๋ฅผ DECODE ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด์„œ ํ‘œํ˜„ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

1
2
3
4
5
6
SELECT
    SUM(DECODE(DEPARTMENT_ID, 10, SALARY, 0)) AS "10"
    ,SUM(DECODE(DEPARTMENT_ID, 20, SALARY, 0)) AS "20"
    ,SUM(DECODE(DEPARTMENT_ID, 30, SALARY, 0)) AS "30"
    ,SUM(DECODE(DEPARTMENT_ID, 400, SALARY,0)) AS "400"
FROM EMPLOYEES;
 

DEPARTMENT_ID๊ฐ€ ๊ฐ๊ฐ 10, 20, 30 ์ธ์ง€ ํ™•์ธํ•˜๊ณ  ํ•ด๋‹น ํ–‰์˜ SALARY ๊ฐ’์„ SUMํ•œ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ค๋‹ˆ๋‹ค. 400๊ฐ™์€ ๊ฒฝ์šฐ์—๋Š” ๋ฐ์ดํ„ฐ์— ์—†์œผ๋ฏ€๋กœ 0์„ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ๋งˆ์ง€๋ง‰ ํ–‰์ผ ์ง€์ •ํ•ด์คฌ์Šต๋‹ˆ๋‹ค.

 

๋Œ“๊ธ€