2013-04-02 126 views
0

我正在尋找更好的方式從我的sql表中檢索數據。尋找有關SQL查詢的幫助

Table 1: User data 
- User Id 
- User Created date 

Table 2: Mapping of the user with a role 
- User Id 
- Role 

Table 3 
Role definition 

Table 4 (may or may not have user data based on his activities on the site) 
User data 
Eg. 
- User Id 
- Total counts of the number of visits made on the portal 

我期待寫(優選1)的查詢量最少做以下

* 我想打印的頂級用戶對每個誰擁有最高總數的角色類型的*

輸出會讀類似以下內容:

Header UserId---Rolename--Total Count 
Row1 Test1 ---Staff --1293 
Row2 Test2 ---Faculty --1223 
Row3 Test3 ---Dean --2283928 

有什麼建議?

+2

考慮提供的DDL(和/或SQLFIDDLE)示出了具有代表性的數據集和所需的結果集在一起以上。 – Strawberry

回答

0

這是你在找什麼:

SELECT a.UserId, b.Role, c.TotalCount 
FROM TABLE1 as a join Table2 as b on a.UserId = b.UserId 
       join Table 4 as c on a.UserId = c.UserId 
ORDER BY c.TotalCount DESC 
LIMIT 3