平均MySQL中的某个列值

时间:2017-06-08 07:24:09

标签: mysql sql select mysqli

我有这个表结构:

id | code | rating 
1  | 300  |   25
2  | 302  |   35
3  | 100  |   50
4  | 100  |   30
5  | 200  |   40
6  | 103  |   45

到目前为止我的查询:

  

SELECT代码,AVG(评级)FROM表GROUP BY代码;

我想平均所有大于300的代码的评级。我尝试在SQL查询上设置IF,但似乎它不起作用。还试过有两个BY组,但它没有工作。我想实现这个结果:

code         |  AVG (rating)
300+ (alias) |  30
100          |  40
200          |  40
103          |  45

4 个答案:

答案 0 :(得分:3)

case when中使用group by

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中的demo

注意:这可以在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)`

答案 1 :(得分:3)

SELECT CODE,AVG(rating) FROM
(
SELECT CASE WHEN code >= 300 THEN '300+' ELSE CODE END AS CODE, rating FROM table 
)Z
GROUP BY code;

您可以尝试上面的代码。

希望这会有所帮助。

答案 2 :(得分:3)

您可以使用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

答案 3 :(得分:2)

根据上述问题中提到的描述,请尝试执行以下SQL select查询作为解决方案。

 select code,avg(rating) from table where code < 300 group by code  
 union 
 select code,avg(rating) from table where code >= 300