[英]Average of grouped rows in SQL
我的下一张桌子叫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
我要执行的查询是:逐月显示蓝色的平均颜色数。
所以我想要下一个结果:
October 0.5
January 0
September 0
March 0.33
我在想类似的东西:
SELECT BALL.Month, avg(BALL.Color)
FROM BALL
WHERE BALL.Color = 'blue'
GROUP BY BALL.Month;
但这没用
您可以使用此方法
SELECT BALL.Month, avg(BALL.Color='Blue')
FROM BALL
GROUP BY BALL.Month;
从1月份分组的balls
选择MONTH,ROUND(AVG(color ='blue'),2)
试试这个查询。 这有点复杂。 但是有效
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
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.