SQL select查询排名

时间:2012-07-26 15:02:57

标签: sql select

我有一个名为logs的表,记录了谁输入或输出数据。 现在我不想得到谁贡献最多并对其进行排名的统计数据。

列是

 Occur_Time | iUser_id | iUsername | oUser_id | oUsername
 --iUser_id is the input persons index from another table that lists the username.
 --iUsername is the input persons name.
 --oUser_id is the index of the person who took the input away.
 --oUsername is the name of the person who took the input away.

现在我不知道谁的投入最多。

我的逻辑:

 Example:
     User_id is 1, name is One.
     Check how many times 1 is repeated on iUser_id = 100 times.
     Check how many times 1 is repeated on oUser_id = 10 times.
     User_id=1 has contributed 90 times.
     Then sort by who has most contribution.

谢谢。

3 个答案:

答案 0 :(得分:0)

Rank功能可能正是您所寻找的。

http://msdn.microsoft.com/en-us/library/ms176102.aspx

答案 1 :(得分:0)

(未测试):

SELECT L.iUsername, 
((SELECT COUNT(1) FROM logs WHERE iUsername=L.iUsername) - 
(SELECT COUNT(1) FROM logs WHERE oUsername=L.iUsername)) as rank  
FROM logs L 
GROUP BY L.iUsername 
ORDER BY rank ASC

答案 2 :(得分:-1)

尝试该查询。

Select user_id, count(user_id) from tablename group by user_id;