How to generate series of dates in postgresql that are repeated every end of the month of another date

751 views Asked by At

I want to generate date data using postgresql function "generate_series" , however I have only advanced as far as the following:

SELECT
    ( DATE_TRUNC( 'month', ld ) + '1 month'::INTERVAL - '1day'::INTERVAL )::DATE AS pe_produc
FROM
    GENERATE_SERIES( TIMESTAMP'2022-01-31', TIMESTAMP'2022-3-31', INTERVAL'1 month' ) AS ld

The result of the previous query:

enter image description here

While the date structure I want to generate is as follows:

enter image description here

How should I modify my query to get the desired result?

Thanks in advance.

1

There are 1 answers

1
Jean On

With cte command I was able to fix it!

SELECT 
         a.pe_produc::date AS pe_produc
        ,b.mes_produc::date AS mes_produc
FROM 
    (SELECT
     generate_series('2022-01-31'::date
                     , '2022-03-31'::date
                     , interval  '1 month') AS pe_produc
     ,generate_series(1, (DATE_PART('month', '2022-03-31'::date) - DATE_PART('month', '2022-01-31'::date)+1)::int) AS b
     ) A 
    ,(SELECT generate_series('2022-01-31'::date
                       ,'2022-03-31'::date
                       , interval  '1 month') AS mes_produc 
     , generate_series(1, (DATE_PART('month', '2022-03-31'::date) - DATE_PART('month', '2022-01-31'::date)+1)::int) AS b
      ) B