滚动累加有两种方式:
1.第一种方式,抱歉我贴了一段自己写的SQL,大家只看蓝色标记的即可
DROP TABLE IF EXISTS tmp.tmp_group_bg_sales_budget_mth_2;
create table tmp.tmp_group_bg_sales_budget_mth_2 STORED AS ORC AS
select
bg_wid
,substr(sales_dt_wid,1,6) AS month_id
,substr(sales_dt_wid,1,4) AS year_id
,sum(coalesce(amt_bf_without_tax,0)) AS amt_bf_without_tax
,sum(coalesce(amt_af_without_tax,0)) AS amt_af_without_tax
,sum(sum(coalesce(amt_bf_without_tax,0))) OVER (PARTITION BY bg_wid,substr(sales_dt_wid,1,4) ORDER BY substr(sales_dt_wid,1,6)) AS amt_bf_without_tax_yth_ytd
,sum(sum(coalesce(amt_af_without_tax,0))) OVER (PARTITION BY bg_wid,substr(sales_dt_wid,1,4) ORDER BY substr(sales_dt_wid,1,6)) AS amt_af_without_tax_yth_ytd
,sum(coalesce(budget_amt_bf_without_tax,0)) AS budget_amt_bf_without_tax
,sum(coalesce(budget_amt_af_without_tax,0)) AS budget_amt_af_without_tax
,sum(sum(coalesce(budget_amt_bf_without_tax,0))) OVER (PARTITION BY bg_wid,substr(sales_dt_wid,1,4)) AS budget_amt_bf_without_tax_yth
,sum(sum(coalesce(budget_amt_af_without_tax,0))) OVER (PARTITION BY bg_wid,substr(sales_dt_wid,1,4)) AS budget_amt_af_without_tax_yth
from tmp.tmp_group_bg_sales_budget_mth_1
GROUP BY
bg_wid
,substr(sales_dt_wid,1,6)
,substr(sales_dt_wid,1,4)
;
1.1 上面蓝色语句解释:
字段解释:amt_bf_without_taxbg_wid是客户消费金额,bg_wid客户ID,substr(sales_dt_wid,1,4)年,substr(sales_dt_wid,1,6)月。
结果解释:蓝色SQL,计算出每个客户年累计。即amt_bf_without_tax_yth_ytd 是将没年月消费数据累加
重点解释:大家想一下,如果将蓝色SQL中ORDER BY substr(sales_dt_wid,1,6)去掉会发生什么,答案是amt_bf_without_tax_yth_ytd 变成每年月数据的总和,而不是累加。
2.第二种方法:直接贴图了
2.1 重点解释:这里面也有累加计算,语句为:
sum(sum(tot_sales)) over(order by month rows between unbounded preceding and current row) current_total_sales。但是大家想下这种方法和第一种方法区别。这种方法会从头到尾计算累加,不区分年,不管有多少年的数据,都是从第一行累加到最后一行;第一种方法会区分年,即在每个年份内,按月累加。
相关连接,链接中的内容很好,是第二种方法的讲解。第一种方法为本人自己摸索出来。欢迎讨论,
https://blog.csdn.net/mlljava1111/article/details/49666925
http://www.blogjava.net/pengpenglin/category/28499.html