我想使用此查询中的值进行更新,但它会说它返回多个值。
UPDATE PO_HEADER
SET TOTAL = (SELECT SUM(LINE_TOTAL) AS "NEW_LINE_TOTAL"
FROM PO_LINE pl, PO_HEADER ph
where ph.IC_PO_HEADER = pl.IC_PO_HEADER
and ph.RELEASE_NUMBER = pl.RELEASE_NUMBER
group by pl.IC_PO_HEADER,pl.FOREIGN_KEY,ph.RELEASE_NUMBER,
ph.REVISION_NUMBER,ph.PO_NUMBER)
from PO_HEADER ph, PO_LINE pl
where ph.IC_PO_HEADER = pl.IC_PO_HEADER;
Msg 512,Level 16,State 1,Line 1
子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。
它如何返回多个列?
答案 0 :(得分:9)
如果此查询返回您想要的信息:
SELECT *, LINE_TOTAL = SUM(l.LINE_TOTAL) OVER
(PARTITION BY l.IC_PO_HEADER, l.RELEASE_NUMBER)
FROM dbo.PO_HEADER AS h
INNER JOIN dbo.PO_LINE AS l
ON h.IC_PO_HEADER = l.IC_PO_HEADER
AND h.RELEASE_NUMBER = l.RELEASE_NUMBER;
然后这可能是您想要的UPDATE查询:
;WITH x AS
(
SELECT h.TOTAL, lt = SUM(l.LINE_TOTAL) OVER
(PARTITION BY l.IC_PO_HEADER, l.RELEASE_NUMBER)
FROM dbo.PO_HEADER AS h
INNER JOIN dbo.PO_LINE AS l
ON h.IC_PO_HEADER = l.IC_PO_HEADER
AND h.RELEASE_NUMBER = l.RELEASE_NUMBER
)
UPDATE x SET TOTAL = lt;
我必须同意戈登,你的分组似乎很奇怪。我不确定我是否做对了(这就是我强烈建议你先运行SELECT的原因。)
答案 1 :(得分:8)
它返回多个列,因为子查询select返回多行。
也许你的意思是这样的:
with toupdate as (
SELECT SUM(LINE_TOTAL) AS "NEW_LINE_TOTAL"
FROM PO_LINE pl join
PO_HEADER ph
on ph.IC_PO_HEADER = pl.IC_PO_HEADER and
ph.RELEASE_NUMBER = pl.RELEASE_NUMBER
group by pl.IC_PO_HEADER, pl.FOREIGN_KEY, ph.RELEASE_NUMBER,
ph.REVISION_NUMBER, ph.PO_NUMBER
)
UPDATE PO_HEADER
SET TOTAL = toupdate. New_Line_Total
from toupdate
where PO_HEADER.IC_PO_HEADER = toupdate.IC_PO_HEADER;
但是,我仍然怀疑这一点,因为你在子查询中按5个字段进行分组,但只加入其中一个字段。在这种情况下,我希望“toupdate”只能在ic_po_header上进行分组。