如何在postgres中获取月份的最后一天?

How to get the last day of month in postgres?

如何在 postgres 中找到最后一天 os 月份? 我有一个日期列以格式(YYYYMMDD)存储为数字(18) 我正在尝试使用

让它过时
to_date("act_dt",'YYYYMMDD') AS "act date"

然后找到这个日期的最后一天: 像这样:

(select (date_trunc('MONTH',to_date("act_dt",'YYYYMMDD')) + INTERVAL '1 MONTH - 1 day')::date)

但它给了我这个错误:

ERROR: Interval values with month or year parts are not supported
  Detail: 
  -----------------------------------------------
  error:  Interval values with month or year parts are not supported
  code:      8001
  context:   interval months: "1"
  query:     673376
  location:  cg_constmanager.cpp:145
  process:   padbmaster [pid=20937]
  -----------------------------------------------

有什么帮助吗?

Postgres 版本:

PostgreSQL 8.0.2 on i686-pc-linux-gnu, compiled by GCC gcc (GCC) 3.4.2 20041017 (Red Hat 3.4.2-6.fc3), Redshift 1.0.874

好的,所以您有一个 numeric(18) 列,其中包含像 20150118 这样的数字。您可以将其转换为日期,例如:

to_date(your_date_column::text, 'YYYYMMDD')

从约会开始,您可以 the last day of the month 喜欢:

(date_trunc('month', your_date_column) + 
    interval '1 month' - interval '1 day')::date;

结合起来,您会得到:

select  (date_trunc('month', to_date(act_dt::text, 'YYYYMMDD')) + 
           interval '1 month' - interval '1 day')::date
from    YourTable;

Example at SQL Fiddle.

如果您使用的是 Amazon AWS Redshift,则可以使用 Redshift 的 LAST_DAY 函数。虽然 Redshift 基于 PostgreSQL,LAST_DAY 函数在 PostgreSQL 中不可用,用于 PostgreSQL .

的解决方案

https://docs.aws.amazon.com/redshift/latest/dg/r_LAST_DAY.html

LAST_DAY( { date | timestamp } )

LAST_DAY returns the date of the last day of the month that contains date. The return type is always DATE, regardless of the data type of the date argument.

例如:

SELECT LAST_DAY( TO_DATE( act_date, 'YYYYMMDD' ) )

对于未来的搜索,Redshift 不接受 INTERVAL '1 month'。而是使用 dateadd(month, 1, date) 记录 here.

要获取月末使用:DATEADD(DAY, -1, (DATE_TRUNC('month', DATEADD(MONTH, 1, date))))

对于正在寻找 Postgres 方法(不使用 Redshift)来解决这个问题的任何人,您可以按照以下方法进行操作:

SELECT (date_trunc('month', '2017-01-05'::date) + interval '1 month' - interval '1 day')::date
AS end_of_month;

'2017-01-05' 替换为您要使用的任何日期。你可以把它变成这样的函数:

create function end_of_month(date)
returns date as
$$
select (date_trunc('month', ) + interval '1 month' - interval '1 day')::date;
$$ language 'sql'
immutable strict;

编辑 Postgres 11+

将其从 的评论中提取出来,您现在可以将区间表达式合并为一个 interval(这使事情变得更短):

select (date_trunc('month', now()) + interval '1 month - 1 day')::date as end_of_month;

-- +--------------+
-- | end_of_month |
-- +--------------+
-- | 2021-11-30   |
-- +--------------+
-- (1 row)

select to_char(date_trunc('month', now() + '01 个月'::间隔) - '01 天'::间隔, 'YYYYmmDD'::text::numeric as end_period_n

date_trunc('month',current_date) + interval '1 month' - interval '1 day'

将任何日期或时间戳截断到月份级别将得到包含该日期的月份的第一天。添加一个月会给您下个月的第一天。然后,删除一天将为您提供所提供日期所在月份的最后一天的日期。