pgSQL date function

时间:2015-09-01 22:19:31

标签: postgresql datetime

How do I tweak this pgSQL SELECT using pgSQL's date functions so it always returns "01" for the day # and "00:00:00" for the time?

SELECT s.last_mailing + '1 month'::interval AS next_edition_date FROM

last_mailing is defined as

last_mailing timestamp without time zone

Examples of the result I am wanting are:

2015-10-01 00:00:00
2015-11-01 00:00:00
2015-12-01 00:00:00

2 个答案:

答案 0 :(得分:1)

You're looking for date_trunc().

psql (9.5alpha2, server 9.4.4)
Type "help" for help.

testdb=# create table subscriptions as select 1 "id", '2015-07-14T12:32'::timestamp last_mailing union all select 2, '2015-08-15T00:00';
SELECT 2
testdb=# select * from subscriptions;                                                                                            id |    last_mailing     
----+---------------------
  1 | 2015-07-14 12:32:00
  2 | 2015-08-15 00:00:00
(2 rows)

testdb=# select *, date_trunc('month', last_mailing) + interval '1 month' AS next_edition_date from subscriptions;
 id |    last_mailing     |  next_edition_date  
----+---------------------+---------------------
  1 | 2015-07-14 12:32:00 | 2015-08-01 00:00:00
  2 | 2015-08-15 00:00:00 | 2015-09-01 00:00:00
(2 rows)

答案 1 :(得分:0)

If you want the first day of the next month, then use:

SELECT (s.last_mailing - (1 - extract(day from s.last_mailing)) * interval '1 day') + 
       interval '1 month'  AS next_edition_date
FROM . . .

If you don't want the time, then use date_trunc():

SELECT date_trunc('day',
                  (s.last_mailing - (1 - extract(day from s.last_mailing)) * interval '1 day') + 
                  interval '1 month'
                 ) AS next_edition_date
FROM . . .