我正在尝试将这两个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
显示具有Data Manager访问权限的所有帐户:
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并获得最高访问权限。
答案 0 :(得分:1)
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
答案 1 :(得分: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