Getting date list in a range in PostgreSQL

后端 未结 8 460
悲&欢浪女
悲&欢浪女 2020-11-28 07:59

I\'d like to get the list of days between the two dates (including them) in a PostgreSQL database. For example, if I had:

  • start date: 29 june
8条回答
  •  一整个雨季
    2020-11-28 08:20

    If the date range should come from a table expression, you could use the following construct:

    DROP TABLE tbl ;
    CREATE TABLE tbl (zdate date NOT NULL );
    INSERT INTO tbl(zdate) VALUES( '2012-07-01') , ('2012-07-09' );
    
    WITH mima AS (
            SELECT MIN(zdate)::timestamp as mi
            , MAX(zdate)::timestamp as ma
            FROM tbl
            )
    SELECT generate_series( mima.mi, mima.ma, '1 day':: interval):: date
    FROM mima
            ;
    

    The casts are needed because generate_series() does not take date arguments.

提交回复
热议问题