PostgreSQL
 SQL >> Database >  >> RDS >> PostgreSQL

Dividere un intervallo di date per anni fiscali in PostgreSQL

Quando serve spezzare un intervallo di date in blocchi per anno fiscale, una soluzione generale usa una tabella di periodi. In alternativa, ecco un approccio autonomo con generate_series, senza tabelle extra.

CREATE TABLE your_table (start_date date, end_date date);
INSERT INTO your_table VALUES ('Jan-17-2008', 'May-20-2009');

SELECT GREATEST(start_date, ('04-01-'||series.year)::date) AS year_start,
       LEAST(end_date, ('03-31-'||series.year + 1)::date) AS year_end
FROM (
 SELECT start_date, end_date,
 generate_series(
  date_part('year', your_table.start_date - INTERVAL '3 months')::int,
  date_part('year', your_table.end_date - INTERVAL '3 months')::int
 ) AS year
 FROM your_table
) AS series(start_date, end_date, year)
ORDER BY start_date;

Il trucco è INTERVAL '3 months': sposta l’anno solare su un anno fiscale che inizia ad aprile. GREATEST e LEAST rifilano ogni finestra fiscale alle date reali di inizio e fine.