简体   繁体   中英

Joining an aggregated table with another table in Sql Server query

I have 2 tables - AfricanRatings and AfricanRatingsAVG . AfricanRatingsAVG is the result of the query:

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 .

A GridView control is used and the data from AfricanRatingsAVG displays just fine in the GridView. My problem: I want to also have data from a third table, AfricanRecipes also included in the same GridView. I have tried JOIN after JOIN with no results. The last two JOINS attempted are:

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.

The second JOIN gives the error message:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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