[英]Joining an aggregated table with another table in Sql Server query
我有2个表AfricanRatings
和AfricanRatingsAVG
。 AfricanRatingsAVG
是查询的结果:
INSERT INTO AfricanRatingsAVG
SELECT RecipeID, COUNT(*) AS Count, AVG(Rating) AS RatingAVG
FROM AfricanRatings
GROUP BY RecipeID
当对AfricanRatingsAVG
进行新输入时,此查询工作正常,并且更新AfricanRatings
。
使用了GridView控件,并且来自AfricanRatingsAVG的数据在GridView中显示得很好。 我的问题:我还想从第三个表获得数据,AfricanRecipes也包含在同一GridView中。 我在JOIN之后尝试了JOIN,但没有结果。 尝试的最后两个JOINS是:
SelectCommand="SELECT *
FROM (SELECT RecipeID, COUNT(*) AS Count, AVG(Rating) AS RatingAVG
FROM AfricanRatings
GROUP BY RecipeID ) AS AfricanRatingsAVG
JOIN (SELECT AfricanRecipes.RecipeID, AfricanRecipes.Category, AfricanRecipes.Name, AfricanRecipes.Description
FROM AfricanRecipes
GROUP BY RecipeID ) AS AfricanRecipes ON (AfricanRatingsAVG.RecipeID = AfricanRecipes.RecipeID)"
和
SelectCommand="SELECT *
FROM (SELECT RecipeID, COUNT(*) AS Count, AVG(Rating) AS RatingAVG
FROM AfricanRatings
GROUP BY RecipeID ) AS AfricanRatingsAVG
JOIN AfricanRecipes.RecipeID, AfricanRecipes.Category, AfricanRecipes.Name, AfricanRecipes.Description
FROM AfricanRecipes
GROUP BY RecipeID AS AfricanRecipes ON (AfricanRatingsAVG.RecipeID = AfricanRecipes.RecipeID)"
上面的第一个JOIN给出错误消息:在选择列表中, AfricanRecipes.Category
列无效,因为它既不包含在聚合函数中也不在GROUP BY
子句中。
第二个JOIN给出错误消息:
','附近的语法不正确
我在上面的连接上尝试了数十种变体,但是没有运气。 任何帮助,将不胜感激。
SELECT
AfricanRatingsAVG.*,
AfricanRecipes.RecipeID,
AfricanRecipes.Category,
AfricanRecipes.Name,
AfricanRecipes.Description
FROM (
SELECT
RecipeID,
COUNT(*) AS RecipeCount,
AVG(Rating) AS RatingAVG
FROM AfricanRatings
GROUP BY RecipeID
) AfricanRatingsAVG
JOIN AfricanRecipes
ON AfricanRatingsAVG.RecipeID = AfricanRecipes.RecipeID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.