使用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(TblC.quantity * (TblA.quantity)) AS Quantity,
然后添加
GROUP BY TblB_1.fooID
在WHERE子句之后,但是导致“选择列表中的TblB_1.name无效,因为它不包含在聚合函数或GROUP BY子句中”错误。
我也尝试使用子查询来完成这项任务,但我也无法完成这项工作,也无法在这里或网上找到我能够适应的例子。谢谢 - 丹
答案 0 :(得分: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