programing

Postgre에서 날짜로부터 연도와 월을 추출하는 방법to_char() 함수를 사용하지 않는 SQL?

magicmemo 2023. 5. 31. 15:47
반응형

Postgre에서 날짜로부터 연도와 월을 추출하는 방법to_char() 함수를 사용하지 않는 SQL?

sql을 선택합니다.SELECT "year-month" from table group by "year-month" AND order by date여기서 year-month - date "filename-01", "filename-12" 형식으로 cause work의 to_char를 선택하지만 "올바른" 순서는 선택하지 않습니다.

to_char(timestamp_column, 'YYYY-MM')
to_char(timestamp, 'YYYY-MM')

당신은 그 주문이 "옳지" 않다고 말하지만, 나는 왜 그것이 잘못되었는지 이해할 수 없습니다(적어도 10000년이 되기 전까지는).

date_part(text, timestamp)

예.

date_part('month', timestamp '2001-02-16 20:38:40'),
date_part('year', timestamp '2001-02-16 20:38:40') 

http://www.postgresql.org/docs/8.0/interactive/functions-datetime.html

메소드를 사용하여 요일(또는 원하는 다른 항목(예: 주, 연도, 일 등)을 잘라냅니다.

주문에서 판매를 월별로 그룹화하는 예:

select
  SUM(amount) as sales,
  date_trunc('month', created_at) as date
from orders
group by date
order by date DESC;

다음을 사용하여 월 이후의 모든 정보를 잘라낼 수 있습니다.

select date_trunc('month',created_at)::date as date 
from orders 
order by date DESC;


예:

입력:

created_at = '2019-12-16 18:28:13'

출력 1:

date_trunc('day',created_at)
// 2019-12-16 00:00:00

출력 2:

date_trunc('day',created_at)::date 
// 2019-12-16

출력 3:

date_trunc('month',created_at)::date 
// 2019-12-01

출력 4:

date_trunc('year',created_at)::date 
// 2019-01-01

첫 번째 옵션

date_trunc('month', timestamp_column)::date

날짜 형식은 모든 달이 첫날부터 유지됩니다.

예:

2016-08-01
2016-09-01
2016-10-01
2016-11-01
2016-12-01
2017-01-01

두 번째 옵션

to_char(timestamp_column, 'YYYY-MM')

@yairchu가 제안한 이 해결책은 제 경우에 잘 작동했습니다.저는 정말 'day' 정보를 버리고 싶었습니다.

EXTRACT 함수 pgSQL을 사용할 수 있습니다.

EX- date = 1981-05-31
EXTRACT(MONTH FROM date)
it will Give 5

자세한 내용은 PGSQL 날짜-시간

다음보다 적은 비용으로 "보다 큰" 기능을 위해 작동합니다.

예:

select date_part('year',txndt)
from "table_name"
where date_part('year',txndt) > '2000' limit 10;

잘 작동하고 있습니다.

을 제외하고는

select date_part('year',txndt)
from "table_name"
where date_part('year',txndt) < '2000' limit 10;

오류가 발생하고 있습니다.

언급URL : https://stackoverflow.com/questions/4531577/how-to-extract-year-and-month-from-date-in-postgresql-without-using-to-char-fu

반응형