DB & SQL/데이터 분석 SQL

데이터 분석 SQL - Date/Timestamp/Time/Interval 타입

PHM 2022. 10. 3. 16:35
Date 일자로서 년, 월, 일 정보를 가짐. YYYY-MM-DD
Timestamp 일자를 시간 정보까지 같이 가짐. YYYY-MM-DD HH24:MI:SS
Time 오직 시간 정보만 가짐 HH24:MI:SS
Interval 얼마나 걸렸는지의 정보 N days HH24:MI_SS

 

문자열을 Date, Timestamp로 변환

to_date('2022-01-01', 'yyyy-mm-dd') 2022-01-01
to_timestamp('2022-01-01', 'yyyy-mm-dd') 2022-01-01 00:00:00.000 +0900
to_timestamp('2022-01-01 14:36:52', 'yyyy-mm-dd hh24:mi:ss') 2022-01-01 14:36:52.000 +0900

 

Date, Timestamp를 문자열로 변환

to_char(hiredate, 'yyyy-mm-dd') 1980-12-17

 

날짜, 시간 포맷팅 패턴

포맷팅 패턴 내용 포맷팅 패턴 내용
hh24 하루중 시간(00-23) month (MONTH) 월 이름
hh12 하루중 시간(01-12) day (DAY) 요일 이름
mi 분(0-59) w 월의 주(1-5)
ss 초(0-59) ww 년의 주(1`52)
yyyy 년도 d 요일, 일요일(1) ~ 토요일(7)
mm 월(01-12) am 또는 pm AM 또는 PM 표시
dd 일(월중 일자 01-31) tz 시간대

 

::date, ::timestamp, ::text를 이용하여 편리하게 형 변환 ( postgresql )

Date를 Timestamp로 변환 select to_date('2022-01-01', 'yyyy-mm-dd')::timestamp
Timestamp를 Text로 변환 select to_timestamp('2022-01-01', 'yyyy-mm-dd')::text
Timestamp를 Date로 변환 select to_timestamp('2022-01-01 14:36:52', 'yyyy-mm-dd hh24:mi:ss')::date

 

extract와 date_part를 이용하여 Date/Timestamp에서 년, 월, 일 / 시간, 분, 초, 추출

select a.*
    , extract(year from hiredate) as year
    , extract(month from hiredate) as month
    , extract(day from hiredate) as day
from hr.emp a;

select a.*
    , date_part('year', hiredate) as year
    , date_part('month', hiredate) as month
    , date_part('day', hiredate) as day
from hr.emp a;

 

날짜와 시간 연산 - interval의 활용

- Date 타입에 숫자값을 더하거나/빼면 숫자값에 해당하는 일자를 더하거나 뺴서 날짜 계산 select to_date('2022-01-01', 'yyyy-mm-dd') + 2 2022-01-03
- Timestamp타입에 숫자값을 더하거나 빼면 오류 발생 select to_timestamp('2022-01-01 14:36:52',
'yyyy-mm-dd hh24:mi:ss') + 7
오류 발생
- Timestamp는 interval 타입을 이용하여 연산 수행 select to_timestamp('2022-01-01 14:36:52',
'yyyy-mm-dd hh24:mi:ss') + inverval '7 hour'
2022-01-01
21:36:52.000

- interval을 더하면 Timestamp 타입이 된다.