我是SQL的新手,已经设法获得足够强大的基本功能,但是我现在正试图从内部联接的结果中找到至少有两个令牌的人:
SELECT
users.[First Name],
users.[Last Name],
IssuedTokens.UserID,
IssuedTokens.TokenID,
Tokens.TokenType
FROM IssuedTokens
INNER JOIN users ON users.ID = IssuedTokens.UserID
INNER JOIN Tokens ON Tokens.number = IssuedTokens.TokenID
GROUP BY IssuedTokens.UserID
HAVING COUNT(*) >= 2
ORDER BY IssuedTokens.UserID
这给出了错误:
列'Users.First Name'在选择列表中无效,因为它是 不包含在聚合函数或GROUP BY子句中。
我很乐意在预先存在的表上使用函数,但还没有看到如何操作连接的结果。如果有人能提供帮助,我将不胜感激。
答案 0 :(得分:0)
您可以在join
之前执行单独的聚合,以获取具有多个令牌的用户。然后,查询的其余部分不需要聚合:
SELECT u.[First Name], u.[Last Name], u.UserID, it.TokenID, t.TokenType
FROM IssuedTokens it INNER JOIN
users u
ON u.ID = it.UserID INNER JOIN
Tokens t
ON t.number = it.TokenID INNER JOIN
(SELECT it.UserId
FROM IssuedTokens it
GROUP BY it.UserId
HAVING COUNT(*) >= 2
) itu
ON itu.UserId = it.UserId
ORDER BY it.UserID;