postgresql查询每个月的最后一天日期,并对未查到的日期结果补0

编程入门 行业动态 更新时间:2024-10-10 12:18:32

postgresql查询每个月的最后一天<a href=https://www.elefans.com/category/jswz/34/1771397.html style=日期,并对未查到的日期结果补0"/>

postgresql查询每个月的最后一天日期,并对未查到的日期结果补0

postgresql查询每个月的最后一天日期,并对未查到的日期结果补0

  • 说明
  • pgsql需要使用函数如下
  • 实现

说明

遇到了一个需求,需要查询每个月月底的最后一天数据,并对未查到的日期结果补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

本文发布于:2024-03-07 16:04:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1718270.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   并对   每个月   postgresql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!