我有2张桌子
First table - userTable
usedID userName
1 someName
2 someOthername
Second Table - ratingTable
userID ratingValue
1 5
1 3
1 5
1 3
2 5
2 5
2 3
2 5
我需要编写一个SQL查询,它将按升序获取所有userID的次数(5星)
答案 0 :(得分:1)
以下是一个例子:
select u.UserId
, count(r.ratingValue)
from userTable u
left join
ratingTable r
on u.userID = r.userID
and r.ratingValue = 5
group by
u.UserID
order by
count(r.ratingValue)
如果结果不需要没有任何五星评级的用户,您甚至可以完全省略userTable。
答案 1 :(得分:1)
SELECT u.userID, u.userName, COUNT(*) AS ratingCount
FROM userTable u
INNER JOIN ratingTable r
ON u.userID = r.userID
AND r.ratingValue = 5
GROUP BY u.userID, u.userName
ORDER BY ratingCount
答案 2 :(得分:0)
我假设您提到5星作为您正在使用的评级系统而不是您只想检索评级为5星的用户。
SELECT u.userName, avg( r.ratingValue ) as averageRating
FROM userTable u
LEFT JOIN ratingTable r ON u.userID = r.userID
GROUP BY u.UserID
ORDER BY avg( r.ratingValue ) desc
这将获得每个用户的平均评分并显示其名称。
userName averageRating
test1 4.5000
test2 1.7500