Getting date list in a range in PostgreSQL

后端 未结 8 462
悲&欢浪女
悲&欢浪女 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:33

    This should do it:

    select date '2012-06-29' + i
    from generate_series(1, (select date '2012-07-3' - date '2012-06-29')) i
    

    If you don't want to repeat the start_date in the subselect things get a bit more complicated:

    with min_max (start_date, end_date) as (
       values (date '2012-06-29', date '2012-07-3')
    ), date_range as (
      select end_date - start_date as duration
      from min_max
    )
    select start_date + i
    from min_max
      cross join generate_series(1, (select duration from date_range)) i;
    

    (See maniek's answer for a much better version of the "no-repeat" problem)

提交回复
热议问题