1

编辑: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
    ...               ...                   ...
4

1 回答 1

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
;
于 2013-06-25T06:17:18.913 回答