请告诉我这个查询有什么问题?
with myFriends as (select objectAuthor,memberId,objectSubject,rating,memberSubjectEq4 from tblRating group by objectAuthor,memberId,objectSubject,rating,memberSubjectEq4)
select authorId,subjectId,(
(
select memberSubjectEq4*(sum(rating)+1) from myFriends where myFriends.objectAuthor=AAA.authorId and myFriends.objectSubject=AAA.subjectId
)
) as XF from tblMC AAA group by authorId,subjectId;
当我在MS SQL Server 2014中运行它时,我将收到以下错误:
列'myFriends.memberSubjectEq4'在选择列表中无效 因为它不包含在聚合函数或 GROUP BY子句。
答案 0 :(得分:0)
使用列执行聚合函数后,必须将其余部分包含在Group By
中with myFriends as (select objectAuthor,memberId,objectSubject,rating,memberSubjectEq4 from tblRating group by objectAuthor,memberId,objectSubject,rating,memberSubjectEq4)
select authorId,subjectId,(
(
select memberSubjectEq4*(sum(rating)+1) from myFriends where myFriends.objectAuthor=AAA.authorId and myFriends.objectSubject=AAA.subjectId
group by memberSubjectEq4
)
) as XF from tblMC AAA group by authorId,subjectId;
答案 1 :(得分:0)
您可以将计算移动到CTE中,然后将其连接到CTE以获得XF数量。
WITH myFriends AS
( SELECT objectAuthor,
objectSubject,
memberSubjectEq4 * (SUM(rating) + 1) AS XF
FROM tblRating
GROUP BY objectAuthor,
objectSubject,
memberSubjectEq4
)
SELECT authorId,
subjectId,
SUM(myFriends.XF) XF
FROM tblMC AAA
LEFT JOIN myFriends ON myFriends.objectAuthor = AAA.authorId
AND myFriends.objectSubject = AAA.subjectId
GROUP BY authorId,
subjectId;