从表中获取总和并尝试更新另一行中的行

时间:2017-11-13 08:13:24

标签: sql

这是我尝试过的一切!

UPDATE DailyBooking
SET RecievedAmount =
(
    SELECT DailyBooking.ID, 
        (SELECT  SUM(RecipientDetails.Amount) FROM RecipientDetails
         WHERE RecipientDetails.DBID = DailyBooking.ID)
    FROM DailyBooking
    INNER JOIN RecipientDetails
        ON RecipientDetails.DBID = DailyBooking.ID 
 ) 

此查询引发错误

  

当选择列表中只能指定一个表达式时   子查询不是用EXISTS引入的。

当我尝试使用where子句时:

 UPDATE DailyBooking SET RecievedAmount=(
    SELECT DailyBooking.ID, 
    (SELECT  SUM(RecipientDetails.Amount) FROM RecipientDetails
    WHERE RecipientDetails.DBID = DailyBooking.ID) FROM DailyBooking INNER JOIN RecipientDetails ON 
    RecipientDetails.DBID =DailyBooking.ID 
     ) where DailyBooking.ID = RecipientDetails.DBID

它会抛出错误:

  

消息4104,级别16,状态1,行6多部分标识符   " RecipientDetails.DBID"无法受约束。

表格! 1表提供总和: RecipientDetails

  1. 具有RecievedAmount列的表:
  2. DailyBooking

    先谢谢..

3 个答案:

答案 0 :(得分:0)

您不能让内部SQL返回超过1的值,因为它的结果是SET收到的结果。

试试这个(不适用于所有数据库,但你没有指定你使用的那个):

UPDATE DailyBooking d
SET d.RecievedAmount =
(
   SELECT  SUM(RecipientDetails.Amount) FROM RecipientDetails            
   WHERE RecipientDetails.DBID = d.ID
) 

答案 1 :(得分:0)

一种选择是将您的聚合查询移动到CTE中,然后使用它加入更新:

WITH cte AS (
    SELECT DBID, SUM(Amount) AS RecievedAmount
    FROM RecipientDetails
    GROUP BY DBID
)
UPDATE db
SET RecievedAmount = t.RecievedAmount
FROM DailyBooking db
INNER JOIN cte t
    ON db.ID = t.DBID;

这应该比通过相关子查询更新来计算总和更好。

答案 2 :(得分:0)

希望这有帮助。

UPDATE DailyBooking
SET RecievedAmount =
 (SELECT  SUM(RecipientDetails.Amount) FROM RecipientDetails
     WHERE RecipientDetails.DBID = DailyBooking.ID)
FROM DailyBooking
INNER JOIN RecipientDetails
    ON RecipientDetails.DBID = DailyBooking.ID