[英]Average of grouped rows in SQL
I have the next table called BALL: 我的下一张桌子叫BALL:
Id ...... Color ........... Month
1 ........ blue ............ October
2 ........ red ............. January
3 ........ green ........... September
4 ........ red ............. October
5 ........ red ............. March
6 ........ blue ............ March
7 ........ red ............. March
The query I want to do is: Show the average number of colors blue month by month. 我要执行的查询是:逐月显示蓝色的平均颜色数。
So I want the next result: 所以我想要下一个结果:
October 0.5
January 0
September 0
March 0.33
I was thinking in something like: 我在想类似的东西:
SELECT BALL.Month, avg(BALL.Color)
FROM BALL
WHERE BALL.Color = 'blue'
GROUP BY BALL.Month;
But It didn't work, 但这没用
You may use this method 您可以使用此方法
SELECT BALL.Month, avg(BALL.Color='Blue')
FROM BALL
GROUP BY BALL.Month;
从1月份分组的balls
选择MONTH,ROUND(AVG(color ='blue'),2)
Try this query. 试试这个查询。 It is little complicated.
这有点复杂。 But works
但是有效
select t1.month,ifnull(t2.occur/t1.tot,0) as percentage from
(select month, count(*) as tot from ball group by month) as t1
left join
(select month, count(*) as occur from ball where color="blue" group by month) as t2
on t1.month=t2.month
http://sqlfiddle.com/#!9/4f1fc/1 http://sqlfiddle.com/#!9/4f1fc/1
select t1.month,t1.mon_cnt,t2.col_cnt from (select month,count(month) mon_cnt from tab1 group by month) t1 join (select month,count(month) col_cnt from tab1 where color='blue' group by month) t2 on (t1.month=t2.month);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.