2010-11-30 53 views
1

我有2個表簡單的SQL SELECT查詢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查詢,將得到按升序排列的所有用戶ID來

+0

好吧,那很簡單。到目前爲止你做了什麼? – 2010-11-30 22:50:07

回答

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 
1

這裏的次數評分(5星)一個例子:

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。

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