选择距离底部最近的项目25%

时间:2017-01-05 14:36:04

标签: oracle math

我有一个查询选择最接近所有汽车平均价格的汽车:

 select  *
    from 
      (
        select USER.CAR.*, abs(CAR_PRICE - ( (select avg(CAR_PRICE) from USER.CAR ) ) ) as PriceDif
        from USER.CAR
        order by PriceDif
      ) 
    where rownum = 1

如何更改此选项以选择最接近最低25%的汽车? 我改成了:

select  *
    from 
      (
        select USER.CAR.*, abs(CAR_PRICE - ( (select avg(CAR_PRICE)*.75 from USER.CAR ) ) ) as PriceDif
        from USER.CAR
        order by PriceDif
      ) 
    where rownum = 1

我的结果接近我的预期,但这是正确的吗?

1 个答案:

答案 0 :(得分:3)

该计算不正确。相反,你需要的是ntile()函数。

https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions101.htm

您正在寻找25%,这意味着您正在寻找四分位数(n = 4)。在下面的查询中,我将展示如何使用此函数查找您要查找的确切价格,同时证明您的计算给出了非常不同的答案。

with
     p ( price ) as (
       select  200 from dual union all
       select  230 from dual union all
       select  400 from dual union all
       select  320 from dual union all
       select  540 from dual union all
       select  290 from dual union all
       select  340 from dual union all
       select  490 from dual union all
       select  380 from dual union all
       select  310 from dual union all
       select 4000 from dual union all
       select  350 from dual
     )
--  end of made-up test data; query begins below this line
select round(avg(price)*0.75, 2) as adjusted_avg_price,
       max(case when quartile = 1 then price end) as first_quartile_price
from   ( select price, ntile(4) over (order by price) as quartile
         from   p
       )
;

ADJUSTED_AVG_PRICE  FIRST_QUARTILE_PRICE
------------------  --------------------
            490.63                   290