小编典典

使用SUM和Group BY进行T-SQL更新

sql

我想使用此查询中的值进行更新,但这意味着它返回多个值。

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。当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。

它如何返回不止一列?


阅读 179

收藏
2021-04-07

共1个答案

小编典典

如果此查询返回所需的信息:

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的原因)。

2021-04-07