如何在SQL中取平均值?

时间:2013-06-20 08:04:37

标签: sql postgresql

编辑:postgresql

我有一些员工的销售数据......表格看起来像这样:

    SalesRep    # of sales/day       NTILE(2)
    --------   --------------      ----------
    Johnny            1                  1
    Johnny            1                  1
    Johnny            4                  1
    Johnny            5                  2
    Johnny            5                  2
    Johnny            5                  2
    Sara              2                  1
    Sara              2                  1
    Sara              2                  1
    Sara              3                  2
    Sara              4                  2
    Sara              5                  2
    ...              ...               ...

我希望找到每位代表每天50%表现最差的平均销售额,以及50%的最佳表现天数

例如,我希望输出表看起来像这样:

    SalesRep    #ofSales Bottom50%    #ofSales Top50%
    --------     --------------         ----------
    Johnny            2                  5
    Sara              2                  4
    ...             ...                ...

到目前为止,我有:

select 
    salesrep,
    case when ntile = 1 then avg(numsales) end,
    case when ntile = 2 then avg(numsales) end,
    ...
    ...
    case when ntile = 10 then avg(numsales) end

    from (

select 
    salesrep,
    numsales,
    NTILE(10) over (PARTITION BY salesrep order by numsales asc) as ntile
from XXX
    ) as YYY

group by salesrep, ntile

这给了我一个奇怪的错误,其中输出包含一堆NULL ...见下表:

    SalesRep     #ofSales Bottom50%    #ofSales Top50%
    --------     --------------         ----------
    Johnny            NULL                  5
    Sara               2                   NULL
    ...               ...                   ...

1 个答案:

答案 0 :(得分:1)

您所需输出中的一行代表一个SalesRep - 因此,您必须按SalesRep 分组。然后,case表达式将内部avg调用作为其参数,如下所示:

select 
    salesrep,
    avg(case when ntile = 1 then avg(numsales) end),
    avg(case when ntile = 2 then avg(numsales) end),
    ...
    ...
    avg(case when ntile = 10 then avg(numsales) end)

from (
    select 
        salesrep,
        numsales,
        NTILE(10) over (PARTITION BY salesrep order by numsales asc) as ntile
    from XXX
) as YYY

group by salesrep, ntile
;

或者,在没有所有花哨格式的情况下重写上述内容:

select 
    salesrep,
    avg(case when ntile = 1 then numsales end),
    avg(case when ntile = 2 then numsales end),
    ...
    ...
    avg(case when ntile = 10 then numsales end)

from (
    select 
        salesrep,
        numsales,
        NTILE(10) over (PARTITION BY salesrep order by numsales asc) as ntile
    from XXX
) as YYY

group by salesrep
;