表具有以下结构:groupTable> lineGroupJoinTable> linesTable(名称是混淆的名称) 我有以下查询返回此错误:
子查询返回的值超过1。这是不允许的 子查询跟随=,!=,<,< =,>,> =或当子查询用作 表达。
问题是我希望由于子查询是组,我不应该得到这个错误。我可能错过了一些东西。
UPDATE dbo.groupTable
SET fieldToUpdate = CASE WHEN fieldToUpdate IS NULL THEN NULL ELSE
(
SELECT sumTable.fieldToSum FROM
dbo.groupTable gt
INNER JOIN
(
SELECT lgjt.groupdId1, lgjt.groupdId2, SUM(lt.fieldToSum) as fieldToSum
FROM lineGroupJoinTable lgjt
INNER JOIN linesTable lt
ON
lt.fieldToSum IS NOT NULL AND lt.fieldToSum > 0 AND
lgjt.lineId1 = lt.lineId1 AND lgjt.lineId2 = lt.lineId2
GROUP BY lgjt.groupdId1, lgjt.groupdId2
) sumTable
ON sumTable.groupdId1 = gt.groupdId1 AND sumTable.groupdId2 = gt.groupdId2
)
END
此变体也尝试遵循建议但返回相同的错误:
UPDATE dbo.groupTable
SET fieldToUpdate = CASE WHEN fieldToUpdate IS NULL THEN NULL ELSE
(
SELECT SUM(sumTable.fieldToSum) FROM
dbo.groupTable gt
INNER JOIN
(
SELECT lgjt.groupdId1, lgjt.groupdId2, SUM(lt.fieldToSum) as fieldToSum
FROM lineGroupJoinTable lgjt
INNER JOIN linesTable lt
ON
lt.fieldToSum IS NOT NULL AND lt.fieldToSum > 0 AND
lgjt.lineId1 = lt.lineId1 AND lgjt.lineId2 = lt.lineId2
GROUP BY lgjt.groupdId1, lgjt.groupdId2
) sumTable
ON sumTable.groupdId1 = gt.groupdId1 AND sumTable.groupdId2 = gt.groupdId2
GROUP BY gt.groupdId1, gt.groupdId2
)
END
答案 0 :(得分:0)
可能是因为dbo.groupTable具有组合id1和id2的多个值。我建议将id1和id2列分组并进行SUM,这种情况下你只有1个结果。
UPDATE dbo.groupTable
SET fieldToUpdate = CASE WHEN fieldToUpdate IS NULL THEN NULL ELSE
(
SELECT SUM(sumTable.fieldToSum) FROM
dbo.groupTable gt
INNER JOIN
(
SELECT lgjt.id1, lgjt.id2, SUM(lt.fieldToSum) as fieldToSum
FROM lineGroupJoinTable lgjt
INNER JOIN linesTable lt
ON
lt.fieldToSum IS NOT NULL AND lt.fieldToSum > 0 AND
lgjt.id3 = lt.id3 AND lgjt.id4 = lt.id4
GROUP BY lgjt.id1, lgjt.id2
) sumTable
ON sumTable.id1 = gt.id1 AND sumTable.id2 = gt.id2
GROUP BY gt.id1, gt.id2
)
END