如何获得百分位而不是排名

时间:2013-05-16 13:08:58

标签: sql sql-server

我有一个SELECT,其中我用于百分位数的一行是:

NTILE(100) OVER(PARTITION BY ItemID ORDER BY SUM(quantity)) as Percentile

数据如下:

ItemID  |  Quantity  |  Price  |  TotalQ
ABC        10           14.50     38
ABC        4            14.25     38
DEF        32           22.41     34
ABC        24           14.10     38
GHI        8            8.50      20
GHI        12           8.60      20
DEF        2            22.30     34

但是,Percentile字段最终只是每个ItemID的每个数量的排名。我希望每一行从顶部开始计算每个交易价格(每行是一笔交易)的累计交易量百分比。

2 个答案:

答案 0 :(得分:2)

在做百分位数时,我更喜欢自己进行计算 - 使用窗口函数很容易。如果您使用的是SQL Server 2012,则可以获得累积总和,并且可以执行以下操作:

select itemId, quantity, price, TotalQ, cast(cumQ as float) / TotQ as Percentile
from (select t.*,
             sum(TotalQ) over (partition by ItemId) as TotQ,
             sum(TotalQ) over (partition by itemId order by TotalQ desc) as cumQ
      from t
     ) t

如果需要,您可以将Percentile乘以100并截断或舍入。

如果您没有SQL Server 2012,则可以使用相关子查询执行相同的操作:

select itemId, quantity, price, TotalQ, cast(cumQ as float) / TotQ as Percentile
from (select t.*,
             sum(TotalQ) over (partition by ItemId) as TotQ,
             (select sum(TotalQ) 
              from t t2
              where t2.itemId = t.ItemId and t2.TotalQ >= t.TotalQ
             ) as cumQ
      from t
     ) t

答案 1 :(得分:1)

这不会起作用吗?

SELECT
   *,
   1E0 * Quantity / TotalQ
FROM
    (
    SELECT 
        *, 
        SUM(Quantity) OVER(PARTITION BY ItemID) AS TotalQ
    FROM
        MyTable
    ) x

或者添加所需的输出