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 -- 下月等于本月的日期,即为上月日期
讯享网

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/117629.html