简体   繁体   English

如何选择年份x年份列表

[英]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". 尝试在psql中构造一个select语句,其中包含的年份列表是(x)“今年”之前的年数。

Modifications of the answer provided in SQL to return list of years since a specific year work for sql, but not for postgres. 修改SQL中提供的答案, 以返回自特定年份以来 sql的年份列表 ,但不是postgres。

Have tried tinkering with generate_series, but unsuccessful. 尝试过修改generate_series,但没有成功。

Use -1 step. 使用-1步。 Example x = 15 例子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/3

https://www.db-fiddle.com/f/shVQnibndNh45uCZxt4jgs/0 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: 稍微更短一些:您还可以使用generate_series函数的数字变量并直接转换EXTRACT函数的返回值,例如:

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: 更重要的是,您可以轻松地将SQL Server代码调整为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. 我建议使用generate_series() ,但我想证明Postgres也支持递归CTE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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