Search code examples
sqloracle-databaseaggregate-functionsunpivot

when more than one condition satisfies, how to group them to calculate average


I'm using Oracle database and want to calculate the mean product price for different regions.

Example:

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

Here product X is sold for 100 in one region and 180 in another region..etc.

Now, for some analytics these are grouped into different ranges which are overlapping and I need to calculate the mean of the price based on the range

Required output is

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

Note that there are many ranges and I have given just 2 for clarity..

I tried like below, but the case is matching first condition and just giving one value for X for [0-200], where I need 2 records

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

How to get 2 records for a match in case statement?.


Solution

  • You can use conditional aggregation and then unpivot as

       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