| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
- Google Excel
- string
- Tkinter
- Python
- matplotlib
- numpy
- dataframe
- Google Spreadsheet
- PySpark
- gas
- c#
- PANDAS
- Java
- Excel
- Kotlin
- SQL
- array
- google apps script
- Github
- list
- PostgreSQL
- django
- hive
- Apache
- 파이썬
- GIT
- Presto
- Redshift
- math
- Today
- Total
달나라 노트
Redshift : date_trunc (지정한 날짜 단위 기준으로 날짜 자르기) 본문
Syntax
date_trunc('datepart', date/timestamp)
date_trunc 함수는 위처럼 사용할 수 있습니다.
주어진 date를 명시한 datepart까지만 남기고 그 이하는 모두 자른 후(모두 가장 작은 값으로 만든 후) timestamp를 반환합니다.
select getdate() as current_dttm --> 2025-09-18 03:23:12.907
, date_trunc('year', getdate()) as trunc_year --> 2025-01-01 00:00:00.000
, date_trunc('quarter', getdate()) as trunc_quarter --> 2025-07-01 00:00:00.000
, date_trunc('month', getdate()) as trunc_month --> 2025-09-01 00:00:00.000
, date_trunc('week', getdate()) as trunc_week --> 2025-09-15 00:00:00.000
, date_trunc('day', getdate()) as trunc_day --> 2025-09-18 00:00:00.000
;
위 예시를 봅시다.
주어진 시점은 2025-09-18 03:23:12.907입니다.
(참고로 getdate() 함수는 현재 시점의 timestamp를 return해주는 함수입니다.)
- date_trunc('year', getdate())
date_trunc에 year를 전달하면 주어진 날짜의 년도인 2025년의 시작점을 return해줍니다.
그래서 2025-01-01 00:00:00.000 이라는 결과가 나왔습니다.
- date_trunc('quarter', getdate())
date_trunc에 quarter를 전달하면 주어진 날짜의 분기인 3분기(9월 18일은 3분기죠)의 시작점을 return해줍니다.
그래서 2025-07-01 00:00:00.000 이라는 결과가 나왔습니다. (3분기의 시작은 7월 1일입니다.)
- date_trunc('month', getdate())
date_trunc에 month를 전달하면 주어진 날짜의 월인 9월의 시작점을 return해줍니다.
그래서 2025-09-01 00:00:00.000 이라는 결과가 나왔습니다.
- date_trunc('week', getdate())
date_trunc에 week를 전달하면 주어진 날짜가 속한 주차의 시작점을 return해줍니다.
2025년 9월 18일은 목요일이며 한 주의 시작은 월요일로 간주됩니다.
그래서 2025-09-15 00:00:00.000 이라는 결과가 나왔습니다. (2025년 9월 15일은 월요일입니다.)
- date_trunc('day', getdate())
date_trunc에 day를 전달하면 주어진 날짜가 속한 일자의 시작점을 return해줍니다.
그래서 2025-09-18 00:00:00.000 이라는 결과가 나왔습니다.
select getdate() as current_dttm --> 2025-09-18 03:23:12.907
, date_trunc('hour', getdate()) as trunc_hour --> 2025-09-18 03:00:00.000
, date_trunc('minute', getdate()) as trunc_minute --> 2025-09-18 03:23:00.000
, date_trunc('second', getdate()) as trunc_second --> 2025-09-18 03:23:12.000
;
date_trunc는 날짜가 아닌 시간에도 사용할 수 있습니다.
위처럼 hour, minute, second를 전달하면 각각 시간, 분, 초를 기준으로 각각의 시작점으로 잘린 값들이 return된 것을 볼 수 있습니다.
'SQL > Redshift' 카테고리의 다른 글
| Redshift : date_add (날짜 더하고 빼기, add or subtract specified interval from a date) (0) | 2021.02.22 |
|---|---|
| Redshift : first_value, last_value (첫 번째 값, 마지막 값 뽑기window function) (0) | 2021.02.18 |
| Redshift : datediff (두 시점간의 차이 구하기) (0) | 2021.01.28 |
| Redshift : to_char (timestamp 또는 date를 문자로 변환) (0) | 2021.01.22 |
| Redshift : to_date (문자를 날짜로 변환) (0) | 2021.01.22 |