본문 바로가기
Database/PostgreSQL

[PostgreSQL] DATE_TRUNC 활용 (연간, 월간, 주간 / 합산, 평균)

by pcm9881 2023. 4. 26.

DATE_TRUNC

지정된 날짜 기준으로 값을 자르고 타임스탬프(timestamp) 또는 간격(interval)을 반환하는 함수입니다.

 

 

예제

 

여기에 아래와 같은 금액 테이블(amounts)이 있다고 가정하시고 보시면 되겠습니다.

 날짜 (컬럼명: trade_date  / 타입:date)  금액 (컬럼명: amount / 타입:bigint)
 2023-04-26  100,000

 

연간 합산 평균

SELECT 
	date_trunc( 'year', trade_date), sum(amount), avg(amount)
FROM amounts 
GROUP BY date_trunc( 'year', trade_date)

 

 

월간 합산 평균

SELECT 
	date_trunc( 'month', trade_date), sum(amount), avg(amount)
FROM amounts 
GROUP BY date_trunc( 'month', trade_date)

 

 

주간 합산 평균

SELECT
	date_trunc( 'week', trade_date), sum(amount), avg(amount)
FROM transactions
GROUP BY date_trunc( 'week', trade_date)

 

참조

[PostgreSQL date_trunc]: https://www.postgresqltutorial.com/postgresql-date-functions/postgresql-date_trunc/

 

PostgreSQL date_trunc Function By Examples

Summary: this tutorial shows you how to use the PostgreSQL date_trunc() function to truncate a timestamp or interval to a specified level of precision. Introduction to the PostgreSQL date_trunc function The date_trunc function truncates a TIMESTAMP or an

www.postgresqltutorial.com

 

728x90

댓글