开发者

Simple SQL Select Query between 2 tables

开发者 https://www.devze.com 2023-01-27 22:10 出处:网络
I have 2 table First table - userTable usedIDuserName 1someName 2someOthername Second Table - ratingTable userID ratingValu开发者_如何学Ce

I have 2 table

First table - userTable

usedID  userName
1          someName
2          someOthername

Second Table - ratingTable

userID ratingValu开发者_如何学Ce
1          5
1          3
1          5
1          3
2          5
2          5
2          3
2          5

I need to write a SQL query that will get all userID in ascending order for number of times rated (5 star)


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


Here's one example:

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)

If the result does not require users without any five star ratings, you can even omit the userTable altogether.


I assume you mentioned 5 stars as the rating system you are using and not that you only wish to retrieve users with ratings of 5 stars.

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

This will get the average rating of each user and display their names.

userName averageRating
test1   4.5000
test2   1.7500
0

精彩评论

暂无评论...
验证码 换一张
取 消