ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด/DataBase

[SQL] ์˜ค๋ผํด ๋‚ด์žฅ ํ•จ์ˆ˜ - ๋‚ ์งœ ํ•จ์ˆ˜ ( ๋‹จ์ผํ–‰ ํ•จ์ˆ˜ )

NaNaRin๐Ÿ™ƒ 2021. 3. 2. 15:47

1. ๋‚ ์งœ ํ•จ์ˆ˜๋ž€

- ๋‚ ์งœ ๋ฐ์ดํ„ฐ๋ฅผ ๋‹ค๋ฃจ๋Š” ํ•จ์ˆ˜

 

2. ํ˜„์žฌ ๋‚ ์งœ ๋ฐ ์‹œ๊ฐ„ ์ •๋ณด๋ฅผ ์ถœ๋ ฅํ•˜๋Š” SYSDATE ํ•จ์ˆ˜

- ์ž…๋ ฅ ๋ฐ์ดํ„ฐ ์—†์ด ํ˜„์žฌ ๋‚ ์งœ ๋ฐ ์‹œ๊ฐ„ ์ •๋ณด๋ฅผ ๊ตฌํ•ด ๋ฐ˜ํ™˜

-- 1. 2. 3.
SELECT 	SYSDATE AS NOW,
		SYSDATE - 1 AS YESTERDAY,
        SYSDATE + 1 AS TOMORROW
FROM	DUAL;

  (1) SYSDATE AS NOW : ์นผ๋Ÿผ ์ด๋ฆ„์ด NOW๋กœ ํ˜„์žฌ ๋‚ ์งœ์™€ ์‹œ๊ฐ„์„ ์ถœ๋ ฅ

  (2) SYSDATE - 1 AS YESTERDAY : ์นผ๋Ÿผ ์ด๋ฆ„์ด YESTERDAY๋กœ ํ˜„์žฌ ๋‚ ์งœ - 1(์–ด์ œ ๋‚ ์งœ)๊ณผ ์‹œ๊ฐ„์„ ์ถœ๋ ฅ

  (3) SYSDATE + 1 AS TOMORROW : ์นผ๋Ÿผ ์ด๋ฆ„์ด TOMORROW๋กœ ํ˜„์žฌ ๋‚ ์งœ + 1(๋‚ด์ผ ๋‚ ์งœ)๊ณผ ์‹œ๊ฐ„์„ ์ถœ๋ ฅ

 

3. ๋ช‡ ๊ฐœ์›” ์ดํ›„ ๋‚ ์งœ๋ฅผ ๊ตฌํ•˜๋Š” ADD_MONTHS ํ•จ์ˆ˜

- ํŠน์ • ๋‚ ์งœ์— ์ง€์ •ํ•œ ๊ฐœ์›” ์ˆ˜ ์ดํ›„ ๋‚ ์งœ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜

ADD_MONTHS([๋‚ ์งœ ๋ฐ์ดํ„ฐ], [๋”ํ•  ๊ฐœ์›” ์ˆ˜])

-- 1. 2.
SELECT 	SYSDATE,
		ADD_MONTHS(SYSDATE, 3)
FROM    DUAL;

  (1) SYSDATE : ํ˜„์žฌ ๋‚ ์งœ์™€ ์‹œ๊ฐ„์„ ์ถœ๋ ฅ

  (2) ADD_MONTHS(SYSDATE, 3) : (1)๋ฒˆ์˜ ํ˜„์žฌ ๋‚ ์งœ์™€ ์‹œ๊ฐ„์—์„œ 3๊ฐœ์›” ์ดํ›„์˜ ๋‚ ์งœ๋ฅผ ์ถœ๋ ฅ

 

4. ๋‘ ๋‚ ์งœ ๊ฐ„์˜ ๊ฐœ์›” ์ˆ˜ ์ฐจ์ด๋ฅผ ๊ตฌํ•˜๋Š” MONTHS_BETWEEN ํ•จ์ˆ˜

- ๋‘ ๋‚ ์งœ ๊ฐ„์˜ ๊ฐœ์›” ์ˆ˜ ์ฐจ์ด๋ฅผ ๋ฐ˜ํ™˜

-- 1. 2. 3.
SELECT 	MONTHS_BETWEEN(HIREDATE, SYSDATE),
		MONTHS_BETWEEN(SYSDATE, HIREDATE),
        TRUNC(MONTHS_BETWEEN(SYSDATE, HIREDATE))
FROM 	EMP;

  (1) MONTHS_BETWEEN(HIREDATE, SYSDATE) : HIREDATE - SYSDATE -> ์Œ์ˆ˜, ์†Œ์ˆ˜์ 

  (2) MONTHS_BETWEEN(SYSDATE, HIREDATE) : SYSDATE - HIREDATE -> ์–‘์ˆ˜, ์†Œ์ˆ˜์ 

  (3) TRUNC(MONTHS_BETWEEN(SYSDATE, HIREDATE)) : SYSDATE - HIREDATE -> ์–‘์ˆ˜, ์†Œ์ˆ˜์  ๋ฒ„๋ฆผ

 

5. ๋Œ์•„์˜ค๋Š” ์š”์ผ, ๋‹ฌ์˜ ๋งˆ์ง€๋ง‰ ๋‚ ์งœ๋ฅผ ๊ตฌํ•˜๋Š” NEXT_DAY, LAST_DAY ํ•จ์ˆ˜

- NEXT_DAY(๋‚ ์งœ ๋ฐ์ดํ„ฐ, ์š”์ผ ๋ฌธ์ž) : ์ž…๋ ฅํ•œ ๋‚ ์งœ ๋ฐ์ดํ„ฐ์—์„œ ๋Œ์•„์˜ค๋Š” ์š”์ผ์˜ ๋‚ ์งœ ๋ฐ˜ํ™˜

- LAST_DAY(๋‚ ์งœ ๋ฐ์ดํ„ฐ) : ์ž…๋ ฅํ•œ ๋‚ ์งœ ๋ฐ์ดํ„ฐ๊ฐ€ ์†ํ•œ ๋‹ฌ์˜ ๋งˆ์ง€๋ง‰ ๋‚ ์งœ๋ฅผ ๋ฐ˜ํ™˜

NEXT_DAY([๋‚ ์งœ ๋ฐ์ดํ„ฐ], [์š”์ผ ๋ฌธ์ž])
LAST_DAY([๋‚ ์งœ ๋ฐ์ดํ„ฐ])

-- 1. 2.
SELECT	SYSDATE,
		NEXT_DAY(SYSDATE, '์›”์š”์ผ'),
      	LAST_DAY(SYSDATE)
FROM	DUAL;

  (1) NEXT_DAY(SYSDATE, '์›”์š”์ผ') : ์˜ค๋Š˜ ๋‚ ์งœ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋Œ์•„์˜ค๋Š” ์›”์š”์ผ ๋‚ ์งœ 2021-03-08 ์˜คํ›„ 4:00:00

  (2) LAST_DAY(SYSDATE) : ์˜ค๋Š˜ ๋‚ ์งœ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ด ๋‹ฌ์˜ ๋งˆ์ง€๋ง‰ ๋‚ ์งœ 2021-03-31 ์˜คํ›„ 4:00:00

 

6. ๋‚ ์งœ์˜ ๋ฐ˜์˜ฌ๋ฆผ, ๋ฒ„๋ฆผ์„ ํ•˜๋Š” ROUND, TRUNC ํ•จ์ˆ˜

- ์ˆซ์ž ๋ฐ์ดํ„ฐ์˜ ๋ฐ˜์˜ฌ๋ฆผ, ๋ฒ„๋ฆผ ์ฒ˜๋ฆฌ์— ์‚ฌ์šฉํ•˜๋Š” ROUND, TRUNC ํ•จ์ˆ˜๋Š” ๋‚ ์งœ ๋ฐ์ดํ„ฐ๋„ ์ž…๋ ฅ ๋ฐ์ดํ„ฐ๋กœ ์‚ฌ์šฉ ๊ฐ€๋Šฅ

- ์†Œ์ˆ˜์  ์œ„์น˜ ์ •๋ณด๋ฅผ ์ž…๋ ฅํ•˜์ง€ ์•Š๊ณ  ๋ฐ˜์˜ฌ๋ฆผ, ๋ฒ„๋ฆผ์˜ ๊ธฐ์ค€์ด ๋  ํฌ๋งท๊ฐ’์„ ์ง€์ •

- ROUND(๋‚ ์งœ ๋ฐ์ดํ„ฐ, ๋ฐ˜์˜ฌ๋ฆผ ๊ธฐ์ค€ ํฌ๋งท) / TRUNC(๋‚ ์งœ ๋ฐ์ดํ„ฐ, ๋ฐ˜์˜ฌ๋ฆผ ๊ธฐ์ค€ ํฌ๋งท)