如何汇总更高级别的加权平均值字段?

时间:2019-05-16 09:28:14

标签: sql

我正在为一个字段计算加权公式为sum(revenue)/ Sum(qty),这是根据以下查询得出的。现在,我将创建一个视图,以存储这些结果,如下面的代码所示。

我的问题是,如果我从视图中选择w_revenue并希望每年查看一次,我将如何汇总以每年显示呢?

select month, sum(revenue)/ Sum(qty) as w_revenue,
year
from my_revenue_table
group by month, year;

create view xyz_rev as 
Select month, sum(revenue)/ Sum(qty) as w_revenue,
year
from my_revenue_table
group by month, year;

select year, w_revenue
from 
xyz_rev ;

2 个答案:

答案 0 :(得分:0)

您将再次聚合W_REVENUE

select year, sum(w_revenue)
from xyz_rev
group by year

答案 1 :(得分:0)

由于仅通过了解几个月的这些值就不可能获得今年的w_revenue,因此我建议将视图更改为:

create view xyz_rev as 
Select month, sum(revenue)/ Sum(qty) as w_revenue,
year
from my_revenue_table
group by ROLLUP(MONTH), year;

通过这种方式,您已经必须将年份数据与单个月的数据一起。