前幾天干活兒的時候,報表中有這么個需求,需要用pgsql查詢兩個日期間的所有年月,下面貼代碼:
1 with recursive t(n) as ( 2 select date('2020-01-01') 3 union all 4 select n+1 from t where n < date('2020-09-30') 5 )select to_char(n, 'yyyy-mm') as month from t group by month order by month;
下面是執行效果:
這里可以看到,只要給出起止日期就可以,執行結果包括起止月份,主要思路就是遞歸,其中recursive函數配合with查詢來實現遍歷,然后查詢的時候,用to_char函數截取年月后分組。
注意:給的日期必須要給到年月日,給年月是不可行的,但是你日期給到時分秒也是可以的
如果這篇博客幫助到了您,是我的榮幸,如果有好的想法,可以在評論區討論哦。