我想返回数据库中“持续时间”列中平均值的20%以内的值。
我想建立在下面的代码上,但是我不想返回其中Duration小于持续时间平均值的值,而是返回所有在AVG(Duration)值的20%之内的值。
Select * From table
Where Duration < (Select AVG(Duration) from table)
答案 0 :(得分:1)
这是一种方法...
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
最后一个可能是最有效的方法。