当前位置:   article > 正文

postgre 通过窗口函数lead或lag计算同环比_pg数据库求环比

pg数据库求环比
  1. SELECT x.stat_dt,x.stat_year,x.stat_month,x.ct,
  2. COALESCE(ROUND((ct-hb)/hb::numeric*100,2),0) hb_dt,
  3. COALESCE(ROUND((ct-tb)/tb::numeric*100,2),0) tb_dt,
  4. (CASE WHEN ROUND((ct-hb)/hb::numeric*100,2) is not null THEN
  5. CONCAT(ROUND((ct-hb)/hb::numeric*100,2),'%')
  6. ELSE
  7. '0'
  8. END) hb_info,
  9. (CASE WHEN ROUND((ct-tb)/tb::numeric*100,2) is not null THEN
  10. CONCAT(ROUND((ct-tb)/tb::numeric*100,2),'%')
  11. ELSE
  12. '0'
  13. END) tb_info
  14. from (
  15. with stat_info as (select to_char(stat_date,'yyyy-mm') stat_dt,to_char(stat_date,'yyyy') stat_year,
  16. to_char(stat_date,'mm') stat_month,count(1) ct
  17. from fdc_tmc_yjzx_contract
  18. where community_id = 381022174
  19. group by stat_dt,stat_year,stat_month
  20. order by stat_dt desc)
  21. SELECT t.*,lead(t.ct,1) over(ORDER BY t.stat_dt desc) hb,lead(t.ct,12) over(ORDER BY t.stat_dt desc) tb from stat_info t
  22. ) x
  23. LIMIT 12

 

lag(value any [, offset integer [, default any ]])

返回偏移值,offset integer是偏移值,正数时前值,负数时后值,没有取到值时用default代替,默认偏移量为0, 默认值为null

lead(value any [, offset integer [, default any ]])

返回偏移值,offset integer是偏移值,正数时取后值,负数时取前值,没有取到值时用default代替

注:使用窗口函数lead或lag,进行同环比计算时,需要注意使用的条件必须是连续的。如果有更好的方式,可以在评论区留言,谢谢!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/765324
推荐阅读
相关标签
  

闽ICP备14008679号