简体   繁体   English

在SQL Server查询中将聚合表与另一个表联接

[英]Joining an aggregated table with another table in Sql Server query

I have 2 tables - AfricanRatings and AfricanRatingsAVG . 我有2个表AfricanRatingsAfricanRatingsAVG AfricanRatingsAVG is the result of the query: AfricanRatingsAVG是查询的结果:

INSERT INTO AfricanRatingsAVG 
SELECT RecipeID, COUNT(*) AS Count, AVG(Rating) AS RatingAVG
FROM AfricanRatings
GROUP BY RecipeID

This query works fine and AfricanRatingsAVG is updated when a new entry is made into AfricanRatings . 当对AfricanRatingsAVG进行新输入时,此查询工作正常,并且更新AfricanRatings

A GridView control is used and the data from AfricanRatingsAVG displays just fine in the GridView. 使用了GridView控件,并且来自AfricanRatingsAVG的数据在GridView中显示得很好。 My problem: I want to also have data from a third table, AfricanRecipes also included in the same GridView. 我的问题:我还想从第三个表获得数据,AfricanRecipes也包含在同一GridView中。 I have tried JOIN after JOIN with no results. 我在JOIN之后尝试了JOIN,但没有结果。 The last two JOINS attempted are: 尝试的最后两个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)"

The first JOIN above gives the error message: Column AfricanRecipes.Category is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. 上面的第一个JOIN给出错误消息:在选择列表中, AfricanRecipes.Category列无效,因为它既不包含在聚合函数中也不在GROUP BY子句中。

The second JOIN gives the error message: 第二个JOIN给出错误消息:

Incorrect syntax near ',' ','附近的语法不正确

I have tried dozens of variations on the above joins with no luck. 我在上面的连接上尝试了数十种变体,但是没有运气。 Any help would be appreciated. 任何帮助,将不胜感激。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM