根据基准行计算百分比/汇总

时间:2018-10-22 02:03:06

标签: sql postgresql

我想计算销售团队与特定团队成员相比的生产力。

给出此查询:

with t1 (rep_id, place_id, sales_qty) as (values
    (0,  1,  3),
    (1,  1,  1),
    (1,  2,  2),
    (1,  3,  4),
    (1,  4,  1),
    (2,  2,  1),
    (2,  3,  3)
)
select
    rep_id,
    count(distinct place_id) as qty_places,
    sum(sales_qty) as qty,
    sum(sales_qty) / count(place_id) as productivity
from 
    t1
group by
    rep_id

结果:

rep_id | qty_places | qty_sales | productivity
---------------------------------------------
0      | 1          | 6         | 6
1      | 4          | 22        | 5
2      | 2          | 9         | 4

我想基于rep_id = 1的生产力来提高团队的生产力,所以我想要这样的东西:

rep_id | qty_places | qty_sales | productivity | productivity %
--------------------------------------------------------------
0      | 1          | 6         | 6            | 1.2
1      | 4          | 22        | 5            | 1           <- Baseline
2      | 2          | 9         | 4            | 0.8

如何在PostgreSQL上使用SQL来实现?

3 个答案:

答案 0 :(得分:1)

这应该可以解决问题

with t1 (rep_id, place_id, sales_qty) as (values
(0,  1,  3),
(1,  1,  1),
(1,  2,  2),
(1,  3,  4),
(1,  4,  1),
(2,  2,  1),
(2,  3,  3)
),
cte as (select
rep_id,
count(distinct place_id) as qty_places,
sum(sales_qty) as qty,
sum(sales_qty) / count(place_id) as productivity
from 
    t1
group by
    rep_id)

select rep_id, qty_places, qty, productivity,
    productivity::numeric/(select productivity::numeric from cte where rep_id = 1) 
    as  productivity_percent from cte

答案 1 :(得分:0)

我们可以尝试在单独的CTE中计算rep_id = 1数字,然后将其交叉连接到当前表:

WITH cte AS (
    SELECT SUM(CASE WHEN rep_id = 1 THEN sales_qty ELSE 0 END) /
        COUNT(CASE WHEN rep_id = 1 THEN 1 END) AS baseline
    FROM t1
)

SELECT
    rep_id,
    COUNT(DISTINCT place_id) AS qty_places,
    SUM(sales_qty) AS qty,
    SUM(sales_qty) / COUNT(place_id) AS productivity,
    (1.0*SUM(sales_qty) / COUNT(place_id)) / t2.baseline AS productivity_pct
FROM t1
CROSS JOIN cte t2
GROUP BY
    t1.rep_id, t2.baseline;

Demo

答案 2 :(得分:0)

仅使用条件聚合。我会使用子查询来做到这一点:

select t.*,
       productivity / max(productivity) filter (where rep_id = 1) over ()
from (select rep_id,
             count(distinct place_id) as qty_places,
             sum(sales_qty) as qty,
             sum(sales_qty)::numeric / count(place_id) as productivity
      from t1
      group by rep_id
     ) t

Here是db <>小提琴。

请注意,您实际上可以在不使用子查询的情况下表达此信息,但是我认为这只会使查询更加复杂。