postgre 通过窗口函数lead或lag计算同环比

SELECT x.stat_dt,x.stat_year,x.stat_month,x.ct,
COALESCE(ROUND((ct-hb)/hb::numeric*100,2),0) hb_dt,
COALESCE(ROUND((ct-tb)/tb::numeric*100,2),0) tb_dt,
(CASE WHEN ROUND((ct-hb)/hb::numeric*100,2) is not null THEN
		CONCAT(ROUND((ct-hb)/hb::numeric*100,2),'%')
	ELSE
		'0'
END) hb_info,
(CASE WHEN ROUND((ct-tb)/tb::numeric*100,2) is not null THEN
		CONCAT(ROUND((ct-tb)/tb::numeric*100,2),'%')
	ELSE
		'0'
END) tb_info
from (
with stat_info as (select to_char(stat_date,'yyyy-mm') stat_dt,to_char(stat_date,'yyyy') stat_year,
to_char(stat_date,'mm') stat_month,count(1) ct 
from fdc_tmc_yjzx_contract
where community_id = 381022174
group by stat_dt,stat_year,stat_month
order by stat_dt desc)
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
) x
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,进行同环比计算时,需要注意使用的条件必须是连续的。如果有更好的方式,可以在评论区留言,谢谢!

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值