简体   繁体   English

SQL-报表中的多个分组

[英]SQL - Multiple grouping within report

I have a table structured similarly to this: 我有一个与此类似的表结构:

ID
Incident_Name
Category
Source

I need a report to show all incidents grouped by category but then the amount of incidents in that category that have a certain source value. 我需要一个报告来显示按类别分组的所有事件,然后显示该类别中具有一定来源值的事件数量。

Category   | Amount | Percentage of Total | Source_1 | Source_2 | Source 3
----------------------------------------------------------------------------
Category 1 | 5      | 25%                 | 1        | 3        | 2
Category 2 | 15     | 75%                 | 10       | 2        | 3

I'm using MySQL - how would I go about doing this. 我正在使用MySQL-我将如何去做。

Grouping and getting the amount/percentage is fine but not sure how I'd go about doing the rest. 分组并获得金额/百分比很好,但不确定我如何去做其余的事情。

SELECT Category, COUNT(*) AS Amount, (COUNT(*) / (SELECT COUNT(*) FROM MyTable)) * 100 AS 'Percentage of Total', 
FROM MyTable
GROUP BY Category;

Any advice 任何建议

I think this is what you are trying to do. 我认为这就是您想要做的。

SELECT Category, 
COUNT(*) AS Amount,
(COUNT(*) / (SELECT COUNT(*) FROM MyTable)) * 100 AS 'Percentage of Total', 
SUM(source=someval1) as Source_1, --this may need a change
SUM(source=someval2) as Source_2, --this may need a change
SUM(source=someval3) as Source_3  --this may need a change
FROM MyTable
GROUP BY Category;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM