2012-07-26 99 views
-1

我有這張表稱爲logs,它記錄了誰輸入或輸出數據。 現在我不想得到誰的貢獻最大和排名的統計數據。用於排序的SQL選擇查詢

列是

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. 

現在我wan't知道誰擁有最多的輸入。

我的邏輯:

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. 

謝謝。

+0

你可以在sqlfiddle上創建表嗎? – Samson 2012-07-26 15:15:07

回答

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 
-1

嘗試該查詢。

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