1

在我疯掉之前,请你帮帮我。我现在在这方面花了一段时间,并求助于你有帮助的好人。我有一个搜索查询:

SELECT  Groups.GroupID, 
        Groups.GroupName, 
        (   SELECT  Sum(SiteRates.SiteMonthlySalesValue) 
            FROM    SiteRates 
            WHERE   InvoiceSites.SiteID = SiteRates.SiteID
        ) AS SumOfSiteRates, 
        (   SELECT  Count(InvoiceSites.SiteID) 
            FROM    InvoiceSites 
            WHERE   SiteRates.SiteID = InvoiceSites.SiteID
        ) AS CountOfSites
FROM    (InvoiceSites 
        INNER JOIN (Groups 
            INNER JOIN SitesAndGroups 
                ON Groups.GroupID = SitesAndGroups.GroupID
        ) ON InvoiceSites.SiteID = SitesAndGroups.SiteID) 
        INNER JOIN SiteRates 
            ON InvoiceSites.SiteID = SiteRates.SiteID
GROUP BY Groups.GroupID

与下表关系

在此处输入图像描述 http://m-ls.co.uk/ExtFiles/SQL-Relationship.jpg

如果没有 GROUP BY 条目,我可以获得我想要的条目列表,但它会按 SiteID 向下钻取结果,而我想按 GroupID 进行分组。我知道这是可能的,但缺乏完成此任务的专业知识。

任何帮助将不胜感激。

4

2 回答 2

2

我认为您需要做的就是添加groups.NameGROUP BY子句中,但是我会采用稍微不同的方法,并尽可能避免使用子查询。由于您已经加入了所有必需的表,因此您可以使用普通的聚合函数:

SELECT  Groups.GroupID, 
        Groups.GroupName, 
        SUM(SiteRates.SiteMonthlySalesValue) AS SumOfSiteRates, 
        COUNT(InvoiceSites.SiteID) AS CountOfSites
FROM    (InvoiceSites 
        INNER JOIN (Groups 
            INNER JOIN SitesAndGroups 
                ON Groups.GroupID = SitesAndGroups.GroupID
        )   ON InvoiceSites.SiteID = SitesAndGroups.SiteID) 
        INNER JOIN SiteRates 
            ON InvoiceSites.SiteID = SiteRates.SiteID
GROUP BY Groups.GroupID, Groups.GroupName;
于 2013-09-24T15:23:41.980 回答
0

我认为您正在寻找的是以下内容:

SELECT Groups.GroupID, Groups.GroupName, SumResults.SiteID, SumResults.SumOfSiteRates, SumResults.CountOfSites
FROM Groups INNER JOIN 
(
SELECT SitesAndGroups.SiteID, Sum(SiteRates.SiteMonthlySalesValue) AS SumOfSiteRates, Count(InvoiceSites.SiteID) AS CountOfSites
FROM SitesAndGroups INNER JOIN (InvoiceSites INNER JOIN SiteRates ON InvoiceSites.SiteID = SiteRates.SiteID) ON SitesAndGroups.SiteID = InvoiceSites.SiteID
GROUP BY SitesAndGroups.SiteID
) AS SumResults ON Groups.SiteID = SumResults.SiteID

此查询将根据您想要的 SiteID 对您的信息进行分组。该查询在链接到 Groups 表的 from 语句中被引用,以提取您想要的组信息。

于 2013-09-24T15:30:26.133 回答