简体   繁体   中英

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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