I have the next table called 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
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);
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.