2013-04-02 90 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