LITTLE BY LITTLE

[4] 데이터 분석 SQL 실습 - Date의 Timestamp의 date_trunc() 본문

SQL/SQL 강의

[4] 데이터 분석 SQL 실습 - Date의 Timestamp의 date_trunc()

위나 2023. 11. 19. 22:10

date와 timestamp 복습 https://noelee.tistory.com/180

 

[3] 데이터 분석 SQL 실습 - Between 조인, Cross 조인, Date와 Timestamp, ::Date, Interval 활용

오늘의 실습 내용 요약 1. BETWEEN 조인 2. CROSS 조인 3. 문자열을 Date, Timestamp로 변환하기 4. ::로 편리하게 형태 변환하기 5. Timestamp 연산 시 Interval 활용하기 Non Equi 조인과 Cross 조인 Equi 조인 : 조인

noelee.tistory.com


잊고있었던 SQL 강의 다시듣기 ..ㅎ.ㅎ

 

date_trunc 함수를 이용하여 년/월/일/시간/분/초 단위 절삭하기  

select trunc(99.9999, 2);
>> 99.99

--date_trunc는 인자로 들어온 기준으로 주어진 날짜를 절삭
select date_trunc('day', '2023-11-19 21:50:26'::timestamp)
>> 2023-11-19 00:00:00.000

 

date타입은 date_trunc하면 타입이 timestamp로 바뀌기 때문에, 유지하고 싶을 경우 ::date로 변환해주기

-- date타입을 date_trunc해도 반환값은 timestamp타입임. 
select date_trunc('day', to_date('2022-03-03', 'yyyy-mm-dd')) as date_01;

-- 만약 date 타입을 그대로 유지하려면 ::date로 명시적 형변환 
select date_trunc('day', '2023-11-19'::date)::date as date_01

>> 2023-11-19
-- 월, 년으로 절단. 
select date_trunc('month', '2023-11-19'::date)::date as date_01;
>>2023-11-01

-- week의 시작 날짜 구하기. 월요일 기준.
select date_trunc('week', '2023-11-19'::date)::date as date_01;
>> 2023-11-13

-- week의 마지막 날짜 구하기. 월요일 기준(일요일이 마지막 날짜)
select (date_trunc('week', '2023-11-19'::date) + interval '6 days')::date as date_01;
>>2023-11-19

-- week의 시작 날짜 구하기. 일요일 기준.
select date_trunc('week', '2023-11-19'::date)::date -1 as date_01;
>> 2023-11-12

-- week의 마지막 날짜 구하기. 일요일 기준(토요일이 마지막 날짜)
select (date_trunc('week', '2023-11-19'::date)::date - 1 + interval '6 days')::date as date_01;
>> 2023-11-18

-- month의 마지막 날짜 
select (date_trunc('month', '2023-11-19'::date) + interval '1 month' - interval '1 day')::date;
>> 2023-11-30

-- 시분초도 절삭 가능. 
select date_trunc('hour', now());
>> 2023-11-19 21:00:00.000 +0900

 

date_trunc는 연,월,일 단위로 Group by 적용 시 자주 사용된다.

drop table if exists hr.emp_test;


-- current_time을 hiretime으로 추가
create table hr.emp_test
as
select a.*, hiredate + current_time as hiretime
from hr.emp a;

select * from hr.emp_test;

-- 입사월로 group by
select date_trunc('month', hiredate) as hire_month, count(*)
from hr.emp_test
group by date_trunc('month', hiredate);

-- 시분초가 포함된 입사일일 경우 시분초를 절삭한 값으로 group by 
select date_trunc('day', hiredate) as hire_day, count(*)
from hr.emp_test
group by date_trunc('day', hiredate);

emp_test 1의 hiretime의 month 별로 count된 모습

 

emp_test 1의 hiretime의 day별로 count된 모습, 시분초를 절삭한 값으로 group by


section4 Group by 와 집계함수 이어서

 

 

 

 

 

Comments