How to extract year and month from date in PostgreSQL without using to_char () function?

I want to select sql: SELECT "year-month" from table group by "year-month" AND order by date , where year-month is the date format "1978-01", "1923-12". select to_char from couse work , but not the "correct" order:

 to_char(timestamp_column, 'YYYY-MM') 
+80
sql postgresql
Dec 25 '10 at 20:29
source share
7 answers
 date_part(text, timestamp) 

eg

 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

+37
Dec 25 '10 at 20:35
source share
 to_char(timestamp, 'YYYY-MM') 

You say that the order is not โ€œcorrectโ€, but I donโ€™t understand why it is wrong (at least until 10,000).

+139
Jun 24 '13 at 8:55
source share

Use the date_trunc method to truncate the day (or what you want, for example, week, year, day, etc.)

Example of grouping sales from orders by month:

 select SUM(amount) as sales, date_trunc('month', created_at) as date from orders group by date order by date DESC; 
+28
Aug 09 '14 at 18:39
source share

You can crop all the information after a month using date_trunc(text, timestamp) :

 select date_trunc('month',created_at)::date as date from orders order by date DESC; 
+11
Jan 20 '16 at 16:51
source share

1st option

 date_trunc('month', timestamp_column)::date 

It will support date format with all months starting from the first day.

Example:

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

Second option

 to_char(timestamp_column, 'YYYY-MM') 

This solution suggested by @yairchu worked fine in my case. I really wanted to give up information about the "day."

+9
Nov 14 '17 at 19:39
source share

You can use the EXTRACT pgSQL function

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

For more information PGSQL Date-Time

+8
Nov 25 '17 at 18:04
source share

It works for more than functions, not less.

For example:

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

works fine.

but for

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

I get an error.

-one
Feb 28 '19 at 13:00
source share



All Articles