簡體   English   中英

在SQL Server查詢中將聚合表與另一個表聯接

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

我有2個表AfricanRatingsAfricanRatingsAVG 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM