如何在PostgreSQL中编写查询以获取一月和其他月份的第一个和最后一个日期

时间:2019-09-16 14:06:42

标签: postgresql

如何获取特定月份的第一个和最后一个日期,即如果我通过特定月份的名称说三月,则应返回输出为01/03/2019和31/03/2019。(对于当前年份)

5 个答案:

答案 0 :(得分:0)

一种简单的方法(也可以在大多数其他数据库上使用)将按月截断传入的日期,以获得该月的第一天。然后,截断日期并加上一个月,然后减去一天,以获得该月的最后一天。

SELECT
    DATE_TRUNC('month', '2019-03-15'::date) AS date_start,
    DATE_TRUNC('month', '2019-03-15'::date + INTERVAL '1 MONTH')
        - INTERVAL '1 DAY' AS date_end;

enter image description here

Demo

答案 1 :(得分:0)

从这里Date LastDay

SELECT date_trunc('MONTH', dtCol)::DATE;

CREATE OR REPLACE FUNCTION last_day(DATE)
RETURNS DATE AS
$$
  SELECT (date_trunc('MONTH', $1) + INTERVAL '1 MONTH - 1 day')::DATE;
$$ LANGUAGE 'sql' IMMUTABLE STRICT;

答案 2 :(得分:0)

如果您想传递值March,则必须修改代码以了解每个月的情况。我不确定是否值得麻烦。无论如何,这是一个基于current_date返回两个值(月初和月末)的代码。如果您想更改日期,可以将'2019-04-13'放在该位置。

SELECT 
    date_trunc('month', current_date) as month_start
  , (date_trunc('month', current_date) + interval '1 month' - interval '1 day')::date as month_end

{DATE_TRUNC函数将日期截断为第一个参数中指定的精度,从而使日期成为给定月份的第一天(取自上例中的current_date)。

对于月底,您需要更多的计算。我一直在生产中使用此功能,它的作用是先将您的日期截断到一个月的第一天,然后再添加一个月再返回一天,这样您就可以确定月底的日期(无论是30、31,或leap年2月的特殊情况。

答案 3 :(得分:0)

对于任何月份,第一天必须是第一天, 就是这样:

make_date(2019, 3, 1)

对于任何月份,最后一天是下个月第一天之前的1天, 就是这样:

make_date(2019, 4, 1)  - integer '1'

抱歉,我没有PostgreSQL环境来测试它是否正确, 所以请自己进行测试。

,顺便说一句, 您可以在此处找到有关日期/时间运算符和函数的更多详细信息: https://www.postgresql.org/docs/current/functions-datetime.html

答案 4 :(得分:0)

从月份名称参数的转换实际上相当简单。创建一个带有月份名称的数组,然后找到参数在数组中的位置,该结果将成为make_date函数的月份值,并从当前日期和日期1中提取年份。以下包含提供日期或月份的重载函数名称和可选年份。

create type first_last_date as ( first_of date, last_of date); 

create or replace function first_last_of_month(date_in date)
returns first_last_date
language sql immutable strict leakproof 
as $$
    select (date_trunc('month', date_in))::date, (date_trunc('month', date_in) + interval '1 month' - interval '1 day')::date ;
$$;

create or replace function first_last_of_month( month_name_in text
                                              , year_in      integer default null
                                              ) 
returns first_last_date 
language sql immutable leakproof 
as $$
select first_last_of_month ( make_date ( coalesce (year_in, extract ('year' from now())::integer)
                                       , array_position(ARRAY['jan','feb','mar','apr','may','jun','jul','aug','sep','nov','dec']
                                                       , lower(substring(month_name_in,1,3)))
                                       ,1 ) );

$$;

-- test    
 Select first_last_of_month('March');

 Select first_last_of_month('February') y2019
      , first_last_of_month('February', 2020) y2020;

Select first_last_of_month(now()::date);