postgresql查询每个月的最后一天日期并对未查到的日期结果补0(操作示例)
目录
- postgresql查询每个月的最后一天日期,并对未查到的日期结果补0
- 说明
- pgsql需要使用函数如下
- 实现
postgresql查询每个月的最后一天日期,并对未查到的日期结果补0
说明
遇到了一个需求,需要查询每个月月底的最后一天数据,并对未查到的日期结果补0。
pgsql需要使用函数如下
使用date_trunc()函数找到指定月第一天

然后对该日期先加一个月在减一个月就能得到你传给的日期的最后一天日期

然后在使用generate_series()函数:你发现这样写不能得到自己的期望结果,有些日期不准确。

最后generate_series()函数结合date_trunc()函数就能达到期望结果:
select to_char((select date_trunc('month',date(t))+interval '1 month'- interval '1 day'),'yyyy-MM-dd') date from generate_series('2021-06-30'::date,'2022-05-31'::date,'1 month') t

然后再将日期与你需要查询的表的日期相关联,使用coalesce(字段,0)函数对值为空进行补0操作,就能查询出你期望的结果。
实现
在实际开发中只需要将2个日期2021-06-30和2022-05-31换成对应的开始日期参数和结束日期参数,那么这个统计结果就是符合期望的结果的了。
SELECT a.time,COALESCE(b.counts,0) as counts from ( SELECT to_char((select date_trunc('month',date(t))+interval '1 month'- interval '1 day'),'yyyy-MM-dd') time FROM generate_series('2021-06-30'::date,'2022-05-31','1 month') t GROUP by time ORDER BY time ) as a LEFT JOIN ( select to_char(starttime,'yyyy-MM-dd') AS starttime, count(starttime) AS counts from rnodbv2.v2_m_ctest_log_info --where to_char(starttime,'yyyy-MM-dd')>='2021-06-30' and to_char(starttime,'yyyy-MM-dd')<='2022-05-31' GROUP BY to_char(starttime,'yyyy-MM-dd') ) as b on a.time=b.starttime order by a.time
结果如下:

到此这篇关于postgresql查询每个月的最后一天日期并对未查到的日期结果补0(操作示例)的文章就介绍到这了,更多相关postgresql查询每个月的最后一天日期内容请搜索电脑手机教程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持电脑手机教程网!