sql - 当满足多个条件时,如何将它们分组以计算平均值
问题描述
我正在使用 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 条匹配记录?
解决方案
您可以使用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
推荐阅读
- python - How do I populate the entry widget when I press the Browse button in tkinter?
- nix - Nix 叠加层中的 Self 和 super
- php - 无法从查询中获取结果
- css - PrimeNG Turbo Table 单元格文本溢出问题
- laravel - 从外部脚本检查 Laravel 5.7 登录
- python - Python:字符串迭代用连字符(或其他字符)替换空格
- mongodb - 在不声明身份验证数据库的情况下登录 mongo shell
- postgresql - 没有 ORDER BY 的窗口函数
- ios - 加载视图控制器时如何更改状态栏样式?
- vue.js - 如何在 Vue Element 中为多个输入设置一个规则?