如何在postgres中找到该月的最后一天?
我有一个日期列,存储为数字(18),格式为(YYYYMMDD)
我正在尝试使用它来使其约会
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
对于任何提出这个问题寻找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', $1) + interval '1 month' - interval '1 day')::date;
$$ language 'sql'
immutable strict;
编辑 Postgres 11+
从评论中删除此内容@Gabriel https://stackoverflow.com/questions/28186014/how-to-get-the-last-day-of-month-in-postgres/45740174#comment115114539_45740174,您现在可以将区间表达式合并为一个interval
(这使得事情变得更短):
select (date_trunc('month', now()) + interval '1 month - 1 day')::date as end_of_month;
-- +--------------+
-- | end_of_month |
-- +--------------+
-- | 2021-11-30 |
-- +--------------+
-- (1 row)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)