简体   繁体   English

MySQL每月选择行并除以总数

[英]mySQL select row per month and divide by total

I have a table that looks like this 我有一张看起来像这样的桌子

May 2015    Red Reports            74
May 2015    Resolved               27
June 2015   Red                    17
June 2015   Resolved               48
June 2015   Blue                    1

How could I query such a table such that I maybe get the months grouped and the rows containing "resolved" divided by the total for that month in the subsequent row? 我如何查询这样的表,以便我可以对月份进行分组,然后将包含“已解决”的行除以下一行中该月的总数? And this subsequent row would be in the format of showing the actual division in parentheses and the percent right after? 并且此后一行的格式为在括号中显示实际的除法以及紧随其后的百分比?

For example, using the previous data one would obtain two columns. 例如,使用先前的数据将获得两列。 The first would be month and the second would be what I'm asking for: 第一个是月份,第二个是我要的:

May 2015    (27/101) 27%
June 2015   (48/66) 73%

This uses a sub-query to grab the resolved value for the month and then uses SUM() to get the total. 这使用子查询来获取当月的解析值,然后使用SUM()来获取总计。

SELECT month, ((
  SELECT value
  FROM `test` t2
  WHERE t2.month = t1.month
    AND t2.name = 'resolved'
) / SUM(value)) AS 'percentage'
FROM `test` t1
GROUP BY month;

Use subqueries to get total and resolved, and concat them: 使用子查询来获取总计和已解决的问题,并进行合并:

select total.y, total.m, concat('(', coalesce(resolved.n, 0), '/', total.n, ')') r
from (
  select year(d) y, month(d) m, sum(n) n 
  from t 
  group by year(d), month(d) ) total
left join (
  select year(d) y, month(d) m, sum(n) n 
  from t 
  where s = 'Resolved' 
  group by year(d), month(d) ) resolved on total.y = resolved.y and total.m = resolved.m;

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

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