MySQL查询帮助

时间:2009-08-06 21:55:25

标签: sql mysql

SELECT username, (SUM(rating)/count(*)) as TheAverage, count(*) as TheCount 
FROM ratings 
WHERE month ='Aug' AND TheCount > 1 
GROUP BY username 
ORDER BY TheAverage DESC, TheCount DESC

我知道这非常接近(我认为),但它说的是'TheCount'在WHERE子句和ORDER子句中不存在。

表格是:

id,用户名,评分,月份

我正在尝试计算每个用户的平均评分,然后按平均评分和评分数量排序结果。

请帮忙。

3 个答案:

答案 0 :(得分:2)

SELECT username, (SUM(rating)/count()) as TheAverage, count() as TheCount 
FROM ratings 
WHERE month ='Aug'
GROUP BY username
HAVING TheCount > 1
ORDER BY TheAverage DESC, TheCount DESC

修改

似乎我看起来不够紧密。

我认为它现在会奏效。

答案 1 :(得分:1)

如果你分组并计算,你需要:

SELECT username, (SUM(rating)/COUNT(*)) as TheAverage, Count(*) as TheCount
    FROM rating
    WHERE month='Aug'
    GROUP BY username
    HAVING TheCount > 1
    ORDER BY TheAverage DESC, TheCount DESC

答案 2 :(得分:1)

您可以使用AVG聚合:

SELECT  username, month, AVG(rating) as TheAverage, COUNT(*) as TheCount
FROM    ratings
WHERE   month ='Aug'
GROUP BY
        username
HAVING  COUNT(*) > 1
ORDER BY
        TheAverage DESC, TheCount DESC

month分组MySQL,因为您的month已被过滤,而MySQL支持在SELECT列表GROUP BY中选择未分组的列{1}}查询(返回组内的随机值)。