3

我想用这个查询中的值更新,但它说它返回多个值。

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;

消息 512,级别 16,状态 1,第 1 行
子查询返回超过 1 个值。当子查询跟随 =、!=、<、<=、>、>= 或子查询用作表达式时,这是不允许的。

它如何返回不止一列?

4

2 回答 2

10

如果此查询返回您想要的信息:

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)。

于 2012-08-10T22:08:08.927 回答
9

它返回多于一列,因为子查询选择返回多行。

也许你的意思更像这样:

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 上分组。

于 2012-08-10T22:01:13.803 回答