2013-03-04 66 views
-1

我有2個表 - AfricanRatingsAfricanRatingsAVGAfricanRatingsAVG是查詢的結果:在Sql Server查詢中加入另一個表的聚集表

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

此查詢工作正常,當一個新條目被製成AfricanRatingsAfricanRatingsAVG被更新。

使用GridView控件,來自AfricanRatingsAVG的數據在GridView中顯示得很好。我的問題:我想從第三個表中獲取數據,AfricanRecipes也包含在同一個GridView中。 JOIN之後,我嘗試了JOIN,但沒有任何結果。最後兩個聯接企圖是:

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

第一個連接上面給出的錯誤信息:列AfricanRecipes.Category是在選擇列表中無效,因爲它不是在聚合函數或包含GROUP BY條款。

第二個連接提供了錯誤信息:

附近有語法錯誤「」

我已經試過幾十以上,沒有運氣加入的變化。任何幫助,將不勝感激。

回答

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 
+0

謝謝Bummi。我試過這個,並得到錯誤消息:關鍵字'FROM'附近的語法錯誤。這是我一直在遇到的。你的建議看起來不錯,但不會奏效。 – user1830924 2013-03-04 22:26:03

+0

@ user1830924看起來像'JOIN'後面只有一個額外的'FROM'。 – 2013-03-04 22:38:10

+0

@MichaelFredrickson謝謝你,試圖更新,看到你的編輯... – bummi 2013-03-04 22:39:40