1、原始数据

模拟数据随机生成:
在这里插入图片描述

2、实现月环比

月环比的做法之一,将本月的费用和上月的费用进行join查询

在这里插入图片描述
由于数据范围是从2021-01-01开始,所以2021-01的上月费用采集不到,即2022-01没有环比值。

月环比代码:

SELECT
	now_month_cost.now_month AS now_month,
	now_month_cost.cost AS now_month_bill_cost,
	last_month_cost.cost AS last_month_bill_cost,
	now_month_cost.cost -  last_month_cost.cost AS month_on_month_cost,
	ROUND((now_month_cost.cost -  last_month_cost.cost)/last_month_cost.cost, 4) AS month_on_month_ratio
FROM
	(
	SELECT
		SUBSTR( bill_date, 1, 7 ) AS now_month,
		sum( bill_cost ) AS cost 
	FROM
		db_test.tt_cost_by_date 
	GROUP BY
		now_month 
	ORDER BY
		now_month DESC,
		cost DESC 
	) now_month_cost
	LEFT JOIN (
	SELECT
		SUBSTR( DATE_ADD( bill_date, INTERVAL 1 MONTH ), 1, 7 ) AS next_month,
		sum( bill_cost ) AS cost 
	FROM
		db_test.tt_cost_by_date 
	GROUP BY
		next_month  
	) last_month_cost 
	ON now_month_cost.now_month = last_month_cost.next_month    -- 下月等于本月的日期,即为上月日期
	
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐