在Sql Server查询中将聚合表与另一个表连接

时间:2013-03-04 21:54:55

标签: sql-server

我有两张桌子 - AfricanRatingsAfricanRatingsAVGAfricanRatingsAVG是查询的结果:

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)"

AND

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给出错误消息:

  

','

附近的语法不正确

我已经尝试了上述连接的几十种变体而没有运气。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

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