PGSQL月份分组查询问题

问题遇到的现象和发生背景

从当前月往前推六个月的统计数据,例如现在是2022-04-06,往前是2022-04,2022-03,2022-02,2022-01,2021-12,2021-11,目前需要一个这样的返回结果

问题相关代码,请勿粘贴截图
运行结果及报错内容
我的解答思路和尝试过的方法

目前有一种方法

select to_char(now() ,'yyyy-MM') as month
union all 
select to_char(now() +'-1 month','yyyy-MM') as month
union all 
select to_char(now() +'-2 month','yyyy-MM') as month
union all 
select to_char(now() +'-3 month','yyyy-MM') as month
union all 
select to_char(now() +'-4 month','yyyy-MM') as month
union all 
select to_char(now() +'-5 month','yyyy-MM') as month

不想用,有没有简洁的?求问

我想要达到的结果

img

给你两种方式,一个是递归,一个是数组转成一列

with RECURSIVE cte as(
select to_char(now() ,'yyyy-MM') as month,-1 lvl
union ALL
select to_char(now() +cast(lvl ||' month' as INTERVAL),'yyyy-MM'),
lvl-1 from cte where lvl>-6)
select month from cte
select unnest( array[ 
to_char(now() ,'yyyy-MM'), 
to_char(now() + '-1 month' ,'yyyy-MM'),
to_char(now() + '-2 month' ,'yyyy-MM'),
to_char(now() + '-3 month' ,'yyyy-MM'),
to_char(now() + '-4 month' ,'yyyy-MM'),
to_char(now() + '-5 month' ,'yyyy-MM')]);

img