1

使用 SQL Server 2005,我有一个查询,该查询从具有数量计算字段的捆绑包中获取子记录。查询看起来像这样:

SELECT  TblB_1.fooID, 
    TblC.quantity * (TblA.quantity) AS Quantity, 
    TblB_1.name AS Name
    FROM    TblB AS TblB_1 INNER JOIN
              TblC ON TblB_1.fooID = TblC.fooID RIGHT OUTER JOIN
              TblB INNER JOIN
                TblA ON TblB.fooID = TblA.fooID ON TblC.parentfooID = TblB.fooID
    WHERE   (TblB.isBundle = 1) AND (TblA.isDeleted = 0)

我需要能够按 id 分组并获得数量字段的总和。我试过用 sum 包裹数量线,如下所示:

SUM(TblC.quantity * (TblA.quantity)) AS Quantity,

然后添加

GROUP BY TblB_1.fooID

在 WHERE 子句之后,但这会导致“TblB_1.name 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中”错误。

我还尝试使用子查询来完成这项任务,但我也无法完成这项工作,也无法在此处或在 Web 上找到我能够适应的示例。谢谢 - 丹

4

1 回答 1

1

您很接近,您需要按所有非聚合字段进行分组。像这样

SELECT  TblB_1.fooID, 
    SUM(TblC.quantity * (TblA.quantity)) AS Quantity, 
    TblB_1.name AS Name
FROM    TblB AS TblB_1 INNER JOIN
          TblC ON TblB_1.fooID = TblC.fooID RIGHT OUTER JOIN
          TblB INNER JOIN
            TblA ON TblB.fooID = TblA.fooID ON TblC.parentfooID = TblB.fooID
WHERE   (TblB.isBundle = 1) AND (TblA.isDeleted = 0)
GROUP BY TblB_1.fooID, TblB_1.name
于 2012-06-14T20:29:40.690 回答