繁体   English   中英

MySQL每月选择行并除以总数

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

我有一张看起来像这样的桌子

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

我如何查询这样的表,以便我可以对月份进行分组,然后将包含“已解决”的行除以下一行中该月的总数? 并且此后一行的格式为在括号中显示实际的除法以及紧随其后的百分比?

例如,使用先前的数据将获得两列。 第一个是月份,第二个是我要的:

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

这使用子查询来获取当月的解析值,然后使用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;

使用子查询来获取总计和已解决的问题,并进行合并:

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