一、業務背景及口徑說明
假設現在有下方這兩張表(sales和dim_date),我們需要通過它們計算銷售額同比增長率。
第一張表是 sales(銷售表),記錄日期和日期對應的銷售額;
第二張表是dim_date(日期維表),記錄日期對應的可比日期(這里是去年同月同天)。
公式如下:
當日銷售額同比增長率=(當日銷售額 - 去年同月同天銷售額) / 去年同月同天銷售額* 100
那么我們該怎么寫 sql 來計算這個同比增長率呢?
二、計算邏輯
計算邏輯:
- 先用銷售表關聯日期維表,獲得每天的可比日期(如2020-01-03的可比日期為2019-01-03),再用上述結果表關聯銷售表,得到可別日期對應的銷售額;
- 根據統計口徑可直接求得。
2.1 MySQL實戰
2.1.1 數據導入
-- DDL: sales drop table if exists test.sales; create table test.sales ( report_date date comment '日期' , sales_amt double comment '銷售額' ) engine=innodb default charset=utf8 ; -- Insert Data insert into test.sales( report_date , sales_amt ) values('2020-01-03', '1000') , ('2020-01-02', '800') , ('2019-01-03', '900') , ('2019-01-02', '1100') ; -- DDL: dim_date create table test.dim_date ( report_date date comment '日期' , date_yoy date comment '去年同月同天' ) engine=innodb default charset=utf8 ; -- Insert Data insert into test.dim_date( report_date , date_yoy ) values('2020-01-03', '2019-01-03') , ('2020-01-02', '2019-01-02') ;
2.1.1 計算邏輯實現
select a.report_date , 100* (a.sales_amt - c.sales_amt) / c.sales_amt '可比增長率' from test.sales a left join test.dim_date b on a.report_date = b.report_date left join test.sales c on b.date_yoy = c.report_date