如何获得每个特定计数分组的记录百分比

时间:2017-12-05 21:38:53

标签: mysql group-by percentage

我在名为users

的表格中有以下数据
   userId   | orgId 
    1       | 1           
    2       | 1            
    3       | 2        
    4       | 2       
    5       | 2        

我在名为activities

的表格中有以下数据
userId   | activityId | type
1        | 11         | a    
1        | 12         | a     
1        | 13         | a
1        | 14         | b
1        | 15         | b
1        | 16         | c     
1        | 17         | c
1        | 18         | c
2        | 19         | a
2        | 20         | a
2        | 21         | c
2        | 22         | c

我需要能够计算每个orgId中的用户百分比:

  1. activities' table where类型中只有1条记录=' c'
  2. activities表中有5条记录type =' c'
  3. activities表中有10条记录type =' c'
  4. activities表格中有50%的记录type =' c'
  5. activities表格中有80%的记录type =' c'
  6. 所以结果应该是这种(希望可能的)格式:

    orgId|% who have 1| % who have 5| % who have 10| % who have 50%| % who have 80% 
    1    | 20         | 54          | 12           | 23            | 32
    2    | 22         | 44          | 32           | 44            | 2
    3    | 28         | 34          | 24           | 11            | 43
    4    | 10         | 14          | 27           | 25            | 45
    

    感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

您可以使用“条件聚合”来获取每位用户的计数和百分比:

select userId,
  sum(type = 'c') as countC,
  sum(type = 'c') * 100 / count(*) as percentC
from activities
group by userId

您的样本数据的结果将是:

| userId | countC | percentC |
|--------|--------|----------|
|      1 |      3 |     37.5 |
|      2 |      2 |       50 |

这可以用作与users表连接的子查询。然后,您可以再次使用“条件聚合”来获得预期结果:

select u.orgId,
  sum(countC = 1) as `only 1`,
  sum(countC >= 5) as `at least 5`,
  sum(countC >= 10) as `at least 10`,
  sum(percentC >= 50) as `at least 50%`,
  sum(percentC >= 80) as `at least 80%`
from (
  select userId,
    sum(type = 'c') as countC,
    sum(type = 'c') * 100 / count(*) as percentC
  from activities
  group by userId
) a
join users u using(userId)
group by u.orgId

您的示例数据不是该查询的最佳数据。但是你会得到:

| orgId | only 1 | at least 5 | at least 10 | at least 50% | at least 80% |
|-------|--------|------------|-------------|--------------|--------------|
|     1 |      0 |          0 |           0 |            1 |            0 |

演示:http://sqlfiddle.com/#!9/b30dae/2