我有一个数据库表,它有三个相关的字段,首先是用户ID,然后一个是提交的节点数,另一个是每个节点“得分”的总和。
我需要能够运行一个查询,它将返回平均分数最高的用户,但我的SQL-fu不是它可能的位置。
干杯!
答案 0 :(得分:2)
这就是你需要的。将int数据类型转换为处理小数的东西很重要,否则你会得到不准确的平均值:
SELECT *, CAST(total_score AS FLOAT) / CAST(total_nodes AS FLOAT) AS average_score
FROM yourtable
ORDER BY CAST(total_score AS FLOAT) / CAST(total_nodes AS FLOAT) DESC
祝你好运!
- 迈克尔
答案 1 :(得分:1)
您在寻找
吗?-- Multiplied by 1.0 to convert it to double
Select top 100 user_id, (1.0 * total_score/total_node) as AvgScore
From YourTable
Order By (total_score/total_node) asc
答案 2 :(得分:0)
SELECT AVG(user.score) AS avg_score
FROM user
GROUP BY user.id
ORDER BY avg_score DESC
答案 3 :(得分:0)
试试这个:
select userid,max(avgscore) as maxscore
from
(select userid,avg(score) as avgscore from usertable group by userid) mytab
答案 4 :(得分:0)
Easer将是
SELECT AVG(user.score1 + user.score2)/2 as average, userid FROM usertable
GROUP BY userid
ORDER BY average
注意你的数据类型。如果分数是整数,您可能首先要将平均值转换为小数。