postgresql - 在 SQL 中查找平均值的百分比 (%) 范围
问题描述
我想返回数据库中 Duration 列中平均值的 20% 以内的值。
我想以下面的代码为基础,但不是返回 Where Duration 小于 duration 的平均值,而是希望返回在 AVG(Duration) 值的 20% 范围内的所有值。
Select * From table
Where Duration < (Select AVG(Duration) from table)
解决方案
这是一种方法...
Select * From table
Where Duration between (Select AVG(Duration)*0.8 from table)
and (Select AVG(Duration)*1.2 from table)
也许这是为了避免重复扫描:
with cte as ( Select AVG(Duration) as AvgDuration from table )
Select * From table
Where Duration between (Select AvgDuration*0.8 from cte)
and (Select AvgDuration*1.2 from cte)
或者
Select table.* From table
cross join ( Select AVG(Duration) as AvgDuration from table ) cj
Where Duration between cj.AvgDuration*0.8 and cj.AvgDuration*1.2
或使用窗口函数:
Select d.*
from (
SELECT table.*
, AVG(Duration) OVER() as AvgDuration
From table
) d
Where d.Duration between d.AvgDuration*0.8 and d.AvgDuration*1.2
最后一种可能是最有效的方法。
推荐阅读
- java - 将突出显示的文本包装到 intellij 上的 System.out.println() 的快捷方式
- sql - TSQL分组并组合json数组中的剩余列
- dialogflow-es - 代理培训失败
- ios - 如何使用字体自动调整大小使标签中的文本居中?
- json - 我应该如何构建返回“最近”值的 RESTful API 操作的 URL?
- excel - 获取下拉框 1 的值并使用下拉框 2 的值作为单元格指示符将其粘贴到何处
- .net - 问题:创建多个 TCP-Server 对象
- python - 如何找到两个轮廓之间的距离
- angular - 为什么显示错误“ReferenceError:未定义响应”
- css - 光滑的滑块表格单元负边距