2

我正在尝试将这两个 SQL 查询组合起来,以在访问列中显示最高计数为 1 的用户名,该列的 itemID 为 2 且访问为 1。

我将如何结合这两个语句来产生这个结果?

显示具有最高权限的帐户:

SELECT UserName, COUNT(Access) AS Count 
FROM Permissions
GROUP BY UserName, Access
HAVING Access = 1
ORDER BY Count DESC

Result:
Username    AccessCount
user1       2
user2       1
user3       2

显示所有具有数据管理员访问权限的帐户:

SELECT UserName FROM Permissions
where itemid = 2 AND Access = 1

Result:
Username
user1
user2

权限表示例数据:

itemID  UserName    Access
1       user1       1
2       user1       1
3       user1       1
1       user2       0
2       user2       1
3       user2       0
1       user3       1
2       user3       0
3       user3       1

结果将是 user1,因为他们可以访问 itemID 2 并且访问次数最多。

4

2 回答 2

1

SQLFiddle 演示在这里

SELECT TOP 1 UserName, COUNT(Access) AS Count 
FROM Permissions ps
WHERE Access = 1
AND
userNAme in 
     (SELECT UserName 
        FROM Permissions
         where itemid = 2 
           AND Access = 1
      )
GROUP BY UserName
ORDER BY Count DESC
于 2013-03-18T12:05:16.070 回答
0
SELECT TOP 1 *
FROM 
(
SELECT [USERNAME] as un,COUNT(ACCESS) AS COUNT
FROM Permissions    
GROUP BY USERNAME,ACCESS
HAVING ACCESS=1     
) a
WHERE EXISTS (SELECT [USERNAME] FROM Permissions WHERE [USERNAME]=a.un and itemid=2)
ORDER BY COUNT DESC
于 2013-03-18T12:12:50.760 回答