如何解决此错误“无法对包含聚合或子查询的表达式执行聚合函数”
SELECT tblPR.PRNO, tblPRMaterial.PRMaterialCode, ISNULL(SUM(DISTINCT tblPRMaterial.PRReqdQty - SUM(tblPOFromPR.Qty)), tblPRMaterial.PRReqdQty) AS PR_Qty
FROM tblPR INNER JOIN
tblPRMaterial ON tblPR.PRNO = tblPRMaterial.PRNO INNER JOIN
tblMaterial ON tblPRMaterial.PRMaterialCode = tblMaterial.MaterialCode LEFT OUTER JOIN
tblPOFromPR ON tblPRMaterial.PRNO = tblPOFromPR.PRNO AND tblPRMaterial.PRMaterialCode = tblPOFromPR.MaterialCode
WHERE (tblPR.PRStatus = 1) AND (tblPRMaterial.PRItemStatus = 0) AND (tblPR.PRType = 'PR') AND (tblPR.PRNO = 56548)
GROUP BY tblPR.PRNO, tblPRMaterial.PRMaterialCode, tblPRMaterial.PRReqdQty
ORDER BY tblPR.PRNO
答案 0 :(得分:0)
您可以尝试以下操作-您需要在isull函数中添加sum(tblPRMaterial.PRReqdQty)
SELECT tblPR.PRNO, tblPRMaterial.PRMaterialCode,
coalesce(SUM(DISTINCT tblPRMaterial.PRReqdQty) - SUM(tblPOFromPR.Qty),
sum(tblPRMaterial.PRReqdQty)) AS PR_Qty
FROM tblPR INNER JOIN
tblPRMaterial ON tblPR.PRNO = tblPRMaterial.PRNO INNER JOIN
tblMaterial ON tblPRMaterial.PRMaterialCode = tblMaterial.MaterialCode LEFT OUTER JOIN
tblPOFromPR ON tblPRMaterial.PRNO = tblPOFromPR.PRNO AND tblPRMaterial.PRMaterialCode = tblPOFromPR.MaterialCode
WHERE (tblPR.PRStatus = 1) AND (tblPRMaterial.PRItemStatus = 0) AND (tblPR.PRType = 'PR') AND (tblPR.PRNO = 56548)
GROUP BY tblPR.PRNO, tblPRMaterial.PRMaterialCode
ORDER BY tblPR.PRNO
答案 1 :(得分:0)
选择和分组依据中的列数必须相同
SELECT tblPR.PRNO,
tblPRMaterial.PRMaterialCode,
ISNULL(SUM(tblPRMaterial.PRReqdQty) - SUM(tblPOFromPR.Qty), sum(tblPRMaterial.PRReqdQty)) AS PR_Qty
FROM tblPR INNER JOIN
tblPRMaterial ON tblPR.PRNO = tblPRMaterial.PRNO INNER JOIN
tblMaterial ON tblPRMaterial.PRMaterialCode = tblMaterial.MaterialCode LEFT OUTER JOIN
tblPOFromPR ON tblPRMaterial.PRNO = tblPOFromPR.PRNO AND tblPRMaterial.PRMaterialCode = tblPOFromPR.MaterialCode
WHERE (tblPR.PRStatus = 1) AND (tblPRMaterial.PRItemStatus = 0) AND (tblPR.PRType = 'PR') AND (tblPR.PRNO = 56548)
GROUP BY tblPR.PRNO, tblPRMaterial.PRMaterialCode
ORDER BY tblPR.PRNO,tblPRMaterial.PRMaterialCode
答案 2 :(得分:0)
因为Aggregate
上不能包含另一个Aggregate
表达式。.也许您可以使用显式来执行Sum
操作。
SELECT
PRNO,
PRMaterialCode,
ISNULL(SUM(SUM_PR), PRReqdQty) AS PR_QTY
FROM
(SELECT
tblPR.PRNO,
tblPRMaterial.PRMaterialCode,
tblPRMaterial.PRReqdQty,
DISTINCT tblPRMaterial.PRReqdQty - SUM(tblPOFromPR.Qty) AS SUM_PR
FROM
tblPR
INNER JOIN tblPRMaterial ON tblPR.PRNO = tblPRMaterial.PRNO
AND (tblPRMaterial.PRItemStatus = 0)
INNER JOIN tblMaterial ON tblPRMaterial.PRMaterialCode = tblMaterial.MaterialCode
LEFT OUTER JOIN tblPOFromPR ON tblPRMaterial.PRNO = tblPOFromPR.PRNO
AND tblPRMaterial.PRMaterialCode = tblPOFromPR.MaterialCode
WHERE
(tblPR.PRStatus = 1)
AND (tblPR.PRType = 'PR')
AND (tblPR.PRNO = 56548)
GROUP BY
tblPR.PRNO,
tblPRMaterial.PRMaterialCode,
tblPRMaterial.PRReqdQty
ORDER BY
tblPR.PRNO) AS Derived_Table
GROUP BY
PRNO,
PRMaterialCode,
PRReqdQty
ORDER BY
PRNO