如何汇总不同粒度级别的加权平均值字段?

时间:2019-05-17 10:34:26

标签: mysql sql

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

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

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

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

select w_revenue 
from xyz.

我该如何做才能每年汇总一次?

Year    Month   Item    Revenue Qty Sum(revenue)/Sum(Qty)
2019    Mar      A       10      2    5
2019    Mar      B       30      3    10
2019    Feb      C       50      1    50
2019    Feb      D       20      2    10

如果我每年看到的话,期望值:

Year    Sum(revenue)/Sum(Qty)
2019    13.75                         (10+30+50+20)/(2+3+1+2)

2 个答案:

答案 0 :(得分:0)

year分组,然后创建另一个视图为

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

并致电

select * from xyz union all
select null, null, a.* from abc a

如果我对您的理解正确的话,可以将它们结合起来。

或每年的收入逐行重复

select x.*,
       (select w_revenue
         from abc
        where year = x.year) as w_revenue_year      
  from xyz x

答案 1 :(得分:0)

您无法从视图中进行所需的聚合。您没有足够的信息。

如果您将视图更改为以下内容:

create view xyz as 
    select year, month, item,
           sum(revenue)/ Sum(qty) as w_revenue,
           sum(qty) as total_qty
    from my_revenue_table
    group by month, year, item;

然后您可以将结果汇总为:

select year, sum(w_revenue * total_qty) / sum(total_qty)
from xyz
group by year;

编辑:

或仅修改视图以获取所需信息:

create view xyz as 
    select year, month, item,
           sum(revenue)/ Sum(qty) as w_revenue,
           sum(qty) as total_qty,
           (sum(sum(revenue)) over (partition by year, item) / 
            sum(sum(qty)) over (partition by year, item)
           ) as w_revenue_year
    from my_revenue_table
    group by month, year, item;