1. DATE_PART
DATE_PART는 날짜 또는 추출하는 함수인데 추출을 활용해서 월 차이를 알 수 있습니다.
* 같은 연도일 경우에만 활용가능합니다.
월 차이 계산 예제
SELECT DATE_PART('month', '2023-04-12'::timestamp) - DATE_PART('month', '2023-02-12'::timestamp); -- 2
2. EXTRACT + AGE
- EXTRACT: 날짜부분을 추출하는 함수입니다.
SELECT EXTRACT('DAY' from '2023-02-03 15:23:22.23242'::timestamp); -- 3
- AGE: 나이를 구하는 함수 첫번째 인수에서 두번째 인수를 뺀 결과를 반환합니다.
SELECT AGE(TIMESTAMP '2023-04-13', TIMESTAMP '2021-02-12'); -- 2 years 2 mons 1 days 0 hours 0 mins 0.0 secs
월 차이 계산 예제
SELECT
EXTRACT(year from AGE(TIMESTAMP '2023-04-13', TIMESTAMP '2022-02-12')) * 12 +
EXTRACT(month from AGE(TIMESTAMP '2023-04-13', TIMESTAMP '2022-02-12')); -- 14
참조
[stackoverflow]: https://stackoverflow.com/questions/11012629/count-months-between-two-timestamp-on-postgresql
Count months between two timestamp on postgresql?
I want to count the number of months between two dates. Doing : SELECT TIMESTAMP '2012-06-13 10:38:40' - TIMESTAMP '2011-04-30 14:38:40'; Returns : 0 years 0 mons 409 days 20 hours 0 mins 0...
stackoverflow.com
[postgresql tutorial date_part]: https://www.postgresqltutorial.com/postgresql-date-functions/postgresql-date_part/
PostgreSQL DATE_PART Function: Extract Year, Month, Week, etc., From a Timestamp
Introduction to the PostgreSQL DATE_PART function Summary: in this tutorial, we will introduce you to the PostgreSQL DATE_PART() function that allows you to retrieve subfields e.g., year, month, week from a date or time value. The DATE_PART() function extr
www.postgresqltutorial.com
[postgresql tutorial extract]: https://www.postgresqltutorial.com/postgresql-date-functions/postgresql-extract/
PostgreSQL EXTRACT: Extracting Year, Month, Day, etc., from a Date
The PostgreSQL EXTRACT() function retrieves a field such as a year, month, and day from a date/time value. Syntax The following illustrates the syntax of the EXTRACT() function: EXTRACT(field FROM source)Code language: PostgreSQL SQL dialect and PL/pgSQL (
www.postgresqltutorial.com
'Database > PostgreSQL' 카테고리의 다른 글
[PostgreSQL] COALESCE null to 0 (0) | 2023.04.24 |
---|---|
[PostgreSQL] DATE_PART 사용하기 (0) | 2023.04.13 |
[PostgreSQL] with문 사용하기 (CTE) (0) | 2023.04.12 |
[PostgreSQL] INSERT INTO SELECT (0) | 2023.04.10 |
[PostgreSQL] 문자열 자르기 (SUBSTRING, SPLIT_PART, REPLACE) (0) | 2023.04.05 |
댓글