我需要从月中获取五天中的最后一天,例如:
1-5 = 5
6-10 = 10
...
26-30/31 = 30/31 (here can be 6 days depending on the month)
我准备了如下函数
create or replace function getfirstdayoffive()
returns date
as
$$
select date_trunc('month', current_date - 5)::date
+ (least(ceil(extract(day from current_date - 5) / 5) * 5,
date_part('day', date_trunc('month', startOp) + interval '1 month - 1 day')))::int - 1;
$$
language sql
stable;
五点的最后一天返回,工作正常。我如何修改它才能识别最后一段时间应该是5天还是6天?
发布于 2021-03-16 21:56:57
尝试以下函数:
CREATE OR REPLACE FUNCTION public.days_in_month(d date)
RETURNS integer
LANGUAGE sql
AS $function$
SELECT date_trunc('month', $1::timestamp + interval '1 month')::date
- date_trunc('month', $1::timestamp)::date;
$function$
发布于 2021-03-17 09:10:43
确定月份的最后一个日期,然后提取日期。如果日期是31天,则返回负6天,否则返回负5天。这假设你想要2月份的最后5天,但是除了2月份,你可以只返回这个月的第25天,因为这是减去5的月份,30天和负6的31天总是返回。注意:这允许参数的默认值为current_date,而不是对current_date进行硬编码。
create or replace
function getfirstdayoffive(parm_date_in date default current_date)
returns date
language sql
immutable strict
as $$
with last_of_mon(eom) as
( select date_trunc('month', parm_date_in) + interval '1 month - 1 day' )
select case when extract(day from eom) = 31
then (eom-interval '6 days')::date
else (eom-interval '5 days')::date
end
from last_of_mon;
$$;
select * from getfirstdayoffive();
select * from getfirstdayoffive(date '2021-08-15');
select * from getfirstdayoffive(date '2020-02-15');
发布于 2021-03-17 16:15:53
嗯,现在我得到了一些类似的东西:
create or replace
function getlastdayoffive(parm_date_in date default current_date)
returns timestamp
language sql
immutable strict
as $$
with last_of_mon(eom) as
( select date_trunc('month', parm_date_in) + interval '1 month - 1 day' )
select case when extract(day from eom) = 31
then (least(ceil(extract(day from parm_date_in - 5) / 5) * 5, date_part('day', date_trunc('month', parm_date_in) + interval '1 month - 1 day')))::timestamp
else (least(ceil(extract(day from parm_date_in - 6) / 6) * 6, date_part('day', date_trunc('month', parm_date_in) + interval '1 month - 1 day')))::timestamp
end
from last_of_mon;
$$;
但是我不能转换成时间戳,怎么做呢?如果我返回integer,那么我就得到了我想要的,但问题是我需要一个格式为YYYY-MM-dd的完整日期
https://stackoverflow.com/questions/66656530
复制相似问题