我有这个表结构:
id | code | rating
1 | 300 | 25
2 | 302 | 35
3 | 100 | 50
4 | 100 | 30
5 | 200 | 40
6 | 103 | 45
到目前为止,这是我的查询:
SELECT code, AVG(rating) FROM table GROUP BY code;
我想对所有大于 300 的代码进行平均评分。我尝试在 SQL 查询上设置一个 IF,但它似乎不起作用。还尝试了两个 group BY,但它不起作用。我想达到这样的结果:
code | AVG (rating)
300+ (alias) | 30
100 | 40
200 | 40
103 | 45
最佳答案
在分组依据
中使用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)`
这是一个demo在 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)`
关于mysql - 平均MySQL中的某个列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44429218/