postgresql获取时间范围内的所有日期

获取所有月份

 select to_char(t,'yyyy-MM') as day
 from 
 generate_series('2018-01-01'::DATE,'2021-10-01', '1 months') as t;
图片.png

获取最近12个月

 select to_char(t,'yyyy-MM') as day
 from 
 generate_series(current_date - interval '12 month' ,now(), '1 months') as t;
图片.png

获取进30天所有日期

 select to_char(t,'yyyy-MM-DD') as day
 from 
 generate_series(current_date - interval '30 day' ,now(), '1 days') as t order by day desc;
图片.png

获取小时(需要采用24小时制)

 select to_char(t,'yyyy-MM-DD HH24') as day
 from 
 generate_series('2021-01-01 01:01:01'::DATE,'2021-01-01 05:01:01', '1 hours') as t order by day desc;
图片.png

如果是判断为空给默认值需要 COALESCE(判断为空的列,默认值) 函数

你可能感兴趣的:(postgresql获取时间范围内的所有日期)