[英]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.