首页 > 解决方案 > 在 SQL 中查找平均值的百分比 (%) 范围

问题描述

我想返回数据库中 Duration 列中平均值的 20% 以内的值。

我想以下面的代码为基础,但不是返回 Where Duration 小于 duration 的平均值,而是希望返回在 AVG(Duration) 值的 20% 范围内的所有值。

Select * From table
Where Duration < (Select AVG(Duration) from table)

标签: postgresqltsql

解决方案


这是一种方法...

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

最后一种可能是最有效的方法。


推荐阅读