【问题标题】:MySQL Group Counting for PercentageMySQL 组计数百分比
【发布时间】:2018-06-12 19:05:48
【问题描述】:

这是我的数据:

BadgeID | Session | Session Type | My_Interest_Area | 
___________________________________________
12345   | PG1     | Symposium    | COPD
12345   | PG1     | Symposium    | Asthma
12345   | PG2     | Symposium    | COPD
12345   | PG2     | Symposium    | Asthma
12345   | PG3     | Workshop     | COPD
12345   | PG3     | Workshop     | Asthma
54321   | PG1     | Symposium    | ARDS
54321   | PG1     | Symposium    | Asthma

我正在尝试得到这个结果:

Interest Area | Symposium Count| Workshop Count
____________________________________
COPD          | 1              | 1
Asthma        | 2              | 1
ARDS          | 1              | 0

最初,我在考虑使用 Where 子句并分隔每个会话类型:

select CDS_Interest_Areas as "Interest Area", round(COUNT(DISTINCT(BadgeID))/count(BadgeID)*100,0) as "Percent" from interest_areas_dataset where CDS_Interest_Areas IS NOT null and `Session Type` = "Symposium"
group by CDS_Interest_Areas

我不需要使用 Where 子句。 我只是想得到结果。

另外,我想得到百分比。表示“兴趣领域”的百分比构成了所说的“会话类型”。

示例: Symposium 有 10% 的哮喘、5% 的 COPD 等……

【问题讨论】:

  • 顺便说一句,这是一种更清晰的提问方式:)

标签: mysql group-by count


【解决方案1】:

您可以使用conditional aggregationdistinct 来获得预期的结果:

select My_Interest_Area,
   count(distinct (case when `Session Type` = 'Symposium' then badgeid end)) SymposiumCount,
   count(distinct (case when `Session Type` = 'Workshop' then badgeid end)) WorkshopCount
from interest_areas_dataset 
group by My_Interest_Area

【讨论】:

  • 为什么要使用“然后徽章”?那有什么用?另外,我可以通过使用 count(distinct (case when Session Type = 'Symposium' then badid end))/100 获得百分比吗??
  • @MichaelClayton - 这称为conditional aggregation。基本上计算所有符合该案例条件的不同徽章。你之前的问题提醒我你想要不同的徽章,如果没有,例如哮喘会返回 3 个专题讨论会。关于百分比,您绝对可以得到一个,但与您之前的问题一样,我不确定您要寻找的确切百分比。如果您使用预期的百分比结果编辑您的问题,它会更清楚。
  • 啊,我看到了“distinct”和“then badge”之间的联系。谢谢,我也编辑了问题。
猜你喜欢
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
相关资源
最近更新 更多