SQL Server:分组依据,表达式失败和分组依据

时间:2019-03-09 17:51:43

标签: sql sql-server

让我们考虑我想在SQL语句中使用Users.imageUsers.description作为表达式,如何添加它们?

如果在SQL语句中添加Users.image并进行分组,则会出现错误。

这有效:

SELECT 
    Users.username, COUNT(Topic.userid) AS upvotes
FROM 
    Users, Role, Topic, Vote, Topic_Vote
WHERE 
    Users.username = 'Adrian'
    AND Users.roleid = Role.roleid
    AND Topic.topicid = Topic_Vote.topicid
    AND Vote.voteid = Topic_Vote.voteid
    AND Topic.userid = Users.userid
GROUP BY 
    Users.username

这是行不通的:

SELECT 
    Users.username, Users.image, COUNT(Topic.userid) AS upvotes
FROM 
    Users, Role, Topic, Vote, Topic_Vote
WHERE 
    Users.username = 'Adrian'
    AND Users.roleid = Role.roleid
    AND Topic.topicid = Topic_Vote.topicid
    AND Vote.voteid = Topic_Vote.voteid
    AND Topic.userid = Users.userid
GROUP BY 
    Users.username, Users.image

1 个答案:

答案 0 :(得分:0)

戈登是正确的,“旧样式”联接存在许多逻辑问题和局限性。 我想您正在寻找类似以下内容的内容-请注意,我没有修复您的原始语法,

WITH UserCounts AS
(
SELECT Users.username, COUNT(Topic.userid) as upvotes
FROM Users, Role, Topic, Vote, Topic_Vote
WHERE Users.username = 'Adrian'
AND Users.roleid = Role.roleid
AND Topic.topicid = Topic_Vote.topicid
AND Vote.voteid = Topic_Vote.voteid
AND Topic.userid = Users.userid
GROUP BY Users.username
)
SELECT UC.*, U.Image
FROM UserCounts AS UC INNER JOIN Users AS U ON UC.UserName = U.UserName