我目前有声明
SELECT ItemName, CONCAT(FirstName, ' ' , LastName) as AuthorName, Avg(DifRating) as 'AvgDifficuilty', Avg(EnjRating) as 'AvgEnjoyment', I.ItemID, A.AuthorID
FROM Rating R
INNER JOIN Item I ON R.ItemID = I.ItemID
INNER JOIN Author A ON I.AuthorID = A.AuthorID
INNER JOIN UserAccount UA ON A.UserID = UA.UserID
GROUP BY R.ItemID
但问题是,不是将AvgDifficuilty和AvgEnjoyment分开,而是奇怪地将它们的数学结合起来,但是将它们分开显示
所以,例如,如果我有DifRatings的vales 3和4以及EnjRatings的3和4,我得到一个3.5的Dif,这是正确的,但然后是一个4 for Enj。
我必须按ItemID进行分组,所以我认为这个问题的解决方案是还要分组购买2个平均值,以便正确计算它们但我似乎无法让它能够按平均数分组
我试过了
GROUP BY R.ItemID, Avg(DifRating)
和
GROUP BY R.ItemID, AvgDifficuilty
但两者都只是出错,所以我不知道怎么做。
TLDR:我如何按平均数分组
任何帮助都会非常感激和抱歉如果我做了一个糟糕的工作解释生病尝试回答任何问题/填写空白因为我不知道我想要的甚至是可能的。
答案 0 :(得分:1)
您应该首先从Rating
表计算平均值,然后再将它们计算到其他表:
SELECT i.ItemName,
i.ItemID,
a.AuthorID,
CONCAT(a.FirstName, ' ', a.LastName) AS AuthorName,
t.AvgDifficulty,
t.AvgEnjoyment
FROM
(
SELECT ItemID,
AVG(DifRating) AS AvgDifficulty,
AVG(EnjRating) AS AvgEnjoyment
FROM Rating
GROUP BY ItemID
) t
INNER JOIN Item i
ON t.ItemID = i.ItemID
INNER JOIN Author a
ON i.AuthorID = a.AuthorID
INNER JOIN UserAccount ua
ON a.UserID = ua.UserID