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