使用generate_series填充PostgreSQL中给定年份的月份列表

时间:2014-02-21 11:35:20

标签: sql database postgresql generate-series

我有以下查询,当输入为日期(2014-01-01)时,会生成给定年份的月份列表:

SELECT to_char(dd, 'Month') 
FROM generate_series(CAST('2014-01-01' AS DATE), date_trunc('month', now()), '1 month') as dd;

  to_char  
-----------
 January  
 February 
(2 rows)

现在,我需要仅传递2014-01-01而不是2014,而是获得相同的结果。

2 个答案:

答案 0 :(得分:2)

SELECT distinct to_char(dd, 'Month') FROM generate_series(to_date('2013', 'YYYY') , date_trunc('month', now()), '1 month') as dd;

答案 1 :(得分:2)

您可以将-01-01附加到年份输入:

SELECT 
  to_char(dd, 'Month') 
FROM 
  generate_series(
      ('2013' || '-01-01')::date, 
      ('2013' || '-01-01')::date + interval '1 year' - interval '1 day', 
      '1 month') as dd;