寻找销售人员排名前5位表现最差的客户

时间:2016-10-31 12:37:07

标签: sql sql-server tsql

我有一个返回数据的视图如下:

|   salesman   |   customer   |  invoiced   |  budgeted   |  difference 
|--------------|--------------|-------------|-------------|--------------
| Joe          |   ACME Ltd   |     1000    |     2000    |    -1 000 
| Sam          |   Apple      |     1500    |     1100    |    +400 
| Joe          |   Apple      |     2000    |     2300    |    -300 
| Kim          |   ACME Ltd   |     1000    |     1500    |    -500

这是返回超过1500行的片段。我想做的是由销售员返回所有行,显示销售人员5个最差的客户销售。因此,每个销售人员将有5行,每个销售人员确实销售给可能与另一个销售人员相同的客户的各个客户......现在我按销售人员按价值查看5个最差的客户。

关于如何实现这一目标的任何想法?

2 个答案:

答案 0 :(得分:1)

由于一个销售人员可以多次为同一家公司开具发票,因此您需要对该组中的发票金额进行平均,然后对该分区进行排名,并排在前五位。如果您正在寻找每个销售员的绝对更差的销售,那么您需要用MIN替换AVG。

SELECT
    *
FROM
(
    SELECT
        salesman,
        customer,
        AverageInvoiced,
        DescendingRank=DENSE_RANK() OVER(PARTITION BY salesman ORDER BY AverageInvoiced DESC)
    FROM
    (
        SELECT 
            salesman,
            customer,
            AverageInvoiced=AVG(invoiced) 
        FROM
            Table
        WHERE
        GROUP BY
            salesman,
            customer    
    )
)AS A
WHERE
    DescendingRank<=5

答案 1 :(得分:0)

我认为你可以使用这个

尝试这个

SELECT
*
    FROM
    (
        SELECT
            salesman,
            customer,
            AverageDiffrence,
            DescendingRank=DENSE_RANK() OVER(PARTITION BY salesman ORDER BY AverageDiffrence DESC)
        FROM
        (
            SELECT 
                salesman,
                customer,
                AverageDiffrence=AVG(difference) 
            FROM
                ireports_salesman_variance
            WHERE
            GROUP BY
                salesman,
                customer    
        )
    )AS A
    WHERE
        DescendingRank<=5