简体   繁体   中英

How to select a list of years x number of years from this year

Trying to construct a select statement in psql with a list of years that is (x) number of years prior to "this year".

Modifications of the answer provided in SQL to return list of years since a specific year work for sql, but not for postgres.

Have tried tinkering with generate_series, but unsuccessful.

Use -1 step. Example x = 15

select * 
from 
    generate_series(
        extract(year from current_date)::int, 
        extract(year from current_date)::int - 15, 
        -1
    )

Another approach:

select 
    extract(year from x.y)
from 
    generate_series(
        current_timestamp, 
        current_timestamp - interval '1 year' * 15, 
        interval '-1 year'
    ) as x(y)

Live test: https://www.db-fiddle.com/f/shVQnibndNh45uCZxt4jgs/3

https://www.db-fiddle.com/f/shVQnibndNh45uCZxt4jgs/0

A bit shorter: you can also use the numeric variant of the generate_series function and cast the return value of the EXTRACT function directly, eg:

SELECT
    EXTRACT(YEAR FROM CURRENT_DATE + ('1y'::interval * x))::text AS year
FROM
    generate_series(-7, -1) AS x
;

If you happen to what the "years" as dates, you can do:

select *
from generate_series(date_trunc('year', now()) - interval '15 year',
                     date_trunc('year', now()),
                     interval '1 year'
                    )

(That is how I would normally want a list of years.)

More importantly, you can easily adapt the SQL Server code to Postgres:

with recursive yearlist as  (
      select extract(year from now()) as year, 1 as lev
      union all
      select yl.year - 1 as year, lev + 1
      from yearlist yl
      where lev < 15
  )
select year
from yearlist
order by year desc;

I recommend generate_series() instead, but I want to demonstrate that Postgres also supports recursive CTEs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM