[英]Average a certain column value in MySQL
我有這個表結構:
id | code | rating
1 | 300 | 25
2 | 302 | 35
3 | 100 | 50
4 | 100 | 30
5 | 200 | 40
6 | 103 | 45
到目前為止,這是我的查詢:
SELECT 代碼,AVG(rating) FROM table GROUP BY 代碼;
我想平均所有代碼的評分大於 300。我嘗試在 SQL 查詢上設置 IF,但似乎不起作用。 也試過有兩個組 BY,但它不起作用。 我想達到這個結果:
code | AVG (rating)
300+ (alias) | 30
100 | 40
200 | 40
103 | 45
在group by
用case when
:
select
case when code >= 300 then '300+' else code end as code,
avg(rating) as `AVG (rating)`
from yourtable
group by case when code >= 300 then 300 else code end
order by `AVG (rating)`
這是 SQLFiddle 中的演示。
注意:這將在 MySQL 中工作,但由於300+
是字符串,因此更嚴格的方法應該首先將代碼轉換為varchar
:
select
case when code >= 300 then '300+' else concat(code, '') end as code,
avg(rating) as `AVG (rating)`
from yourtable
group by case when code >= 300 then '300+' else concat(code, '') end
order by `AVG (rating)`
SELECT CODE,AVG(rating) FROM
(
SELECT CASE WHEN code >= 300 THEN '300+' ELSE CODE END AS CODE, rating FROM table
)Z
GROUP BY code;
你可以試試上面的代碼。
您可以使用case
表達式將所有大於 300 的代碼組合在一起:
SELECT CASE WHEN code >= 300 THEN '300+'
ELSE CAST(code AS CHAR)
END,
AVG(rating)
FROM table
GROUP BY CASE WHEN code >= 300 THEN '300+'
ELSE CAST(code AS CHAR)
END
根據上述問題中提到的描述,請嘗試執行以下 SQL 選擇查詢作為解決方案。
select code,avg(rating) from table where code < 300 group by code
union
select code,avg(rating) from table where code >= 300
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.