1. 程式人生 > >psql計算環比和同比

psql計算環比和同比

\c dw; –連線到資料庫

drop table if exists stg.d_mars_rate_hb_1 ;

create table if not exists stg.d_mars_rate_hb_1(
category_1 TEXT,
date DATE,
quantity numeric(30,16)
);

insert into stg.d_mars_rate_hb_1(
category_1,
date,
quantity
)select
category_1,
date,
quantity
from stg.d_mars_order_date ;–從表裡面選出需要的欄位備用

drop table if exists stg.d_mars_cat1_month_hb;
create table if not exists stg.d_mars_cat1_month_hb(
category_1 TEXT,
hb NUMERIC(30,16)
);

insert into stg.d_mars_cat1_month_hb
//計算出每天category_1對應的值作為原表
with every as (
select category_1,date,sum(quantity) as quantity
from stg.d_mars_rate_product group by category_1,date order by date),

//計算出最近一天的category_1的對應值作為副表1
max_date as(
select category_1, max(date) as date from every where quantity is not null group by category_1),

//將副表1與原表left join 得到最近一個月的值,因為之前的原表沒有quantity欄位,所以left join一下得到quantity欄位
quantity as(
select d.category_1,r.date,d.quantity
from max_date r
left join every d
on r.category_1 = d.category_1 and d.date > (r.date - interval ‘1 month’)::date and d.date <= r.date ),
//又將副表1與原表left join得到的表作為副表2
hb_1 as(
select a.category_1,
//最近一個月的quantity
sum(case when a.date = e.date then a.quantity end) as current_quantity,
//上一個月的quantity,如果求同比的話,將’1 month ’ 換成’12 month’
sum(case when (e.date > (a.date - interval ‘1 month’)::date and e.date <= a.date) then e.quantity end) as preview_quantity
from quantity a
left join every e
on a.category_1 = e.category_1
group by a.category_1
),
result as(
select category_1,(current_quantity - preview_quantity )/ preview_quantity as hb
from hb_1 )
select * from result ;

環比增長計算公式:(這個月的quantity-上個月的quantity)/上個月的quantity
同比增長計算公式:(這個月的quantity-去年同月的quantity)/去年同月的quantity