首页 > 解决方案 > 当满足多个条件时,如何将它们分组以计算平均值

问题描述

我正在使用 Oracle 数据库,想计算不同地区的平均产品价格。

例子:

prod,amt,price
X,100,1
X,180,2
X,250,3
Y,90,2
Y,170,3
Y,280,3

在这里,产品 X 在一个地区的售价为 100,在另一个地区售价为 180……等等。

现在,对于某些分析,它们被分组为重叠的不同范围,我需要根据范围计算价格的平均值

所需的输出是

prod,rang(Amt),mean(price),
X,[0-200],1.5,
X,[150-300],2.5,
Y,[0-200],2.5,
Y,[150-300],3,

请注意,有很多范围,为了清楚起见,我只给出了 2 个。

我尝试如下,但case匹配第一个条件,并且只为 [0-200] 的 X 提供一个值,我需要 2 条记录

select prod, amt, price, 
case 
when amt between 0 and 200 then amt
when amt between 150 and 300 then amt
end as rng
from tablea

如何在 case 语句中获取 2 条匹配记录?

标签: sqloracleaggregate-functionsunpivot

解决方案


您可以使用conditional aggregation然后unpivot作为

   select prod_a as "Prod",
          prod as "Range of Amounts",
          value as "Mean Price"
     from  
            (
            with tablea(prod,amt,price) as
            (
              select 'X',100,1 from dual union all
              select 'X',180,2 from dual union all
              select 'X',250,3 from dual union all
              select 'Y',90, 2 from dual union all
              select 'Y',170,3 from dual union all
              select 'Y',280,3 from dual 
            )
            select prod as prod_a,  
            avg(case when amt between 0 and 200 then price end) as avg_0_200,
            avg(case when amt between 150 and 300 then price end) as avg_150_300
            from tablea a
            group by prod
             ) b  
    unpivot(value for prod in(avg_0_200,avg_150_300))
    order by prod_a;

   Prod  Range of Amounts   Mean Price
   ----  ----------------    ----------
   X     AVG_0_200              1.5
   X     AVG_150_300            2.5
   Y     AVG_0_200              2.5
   Y     AVG_150_300            3

Rextester Demo


推荐阅读