如何根据他们的ID来计算金额

时间:2014-04-16 06:04:14

标签: sql sql-server

我在SQL Server 2008 Express中有一个包含2个表的数据库。

我的问题如下:我想创建一个触发器来对第一个表中的某些值求和,并将总和复制到第二个。

例如,第一个表(Head)有5列:

  ID    Transaction    Acount    Date        Total_sum

   1    some text      acount1   2014.04.15   300
   2    some text      acount2   2014.04.15   500
   3    some text      acount1   2014.04.15   200

第二个表事务:

HeadID金额备注

1       100        test1
1       200        test2
2       500        test3
3       100        test3
3       100        test4 

所以最后我想在Transaction中汇总值,如果它们具有相同的HeadID并将结果复制到Head表中。 (Total_sum列)。也许首先我可以找到'Head'表中的最后一个ID,并在'Transaction'表中对HeadID-s进行分组并对值进行求和

请帮助我!

4 个答案:

答案 0 :(得分:0)

您可以使用JOIN更新表格

UPDATE h
SET h.Total_sum = t.sumTotal
FROM Head h
INNER JOIN 
(
SELECT HeadID,SUM(Amount) as sumTotal
FROM [Transaction]
GROUP BY HeadID
) t
ON h.ID=t.HeadID

答案 1 :(得分:0)

或许如下:

create trigger TransactionInsertUpdateDelete
on Transaction
for insert, update, delete
as
begin
    update H
    set Total_sum = 
        -- set the total sum to the sum of all records for this head id in transaction
        (select sum(Amount) 
        from Transaction as T
        where T.HeadID = H.HeadID
        )
    from Head as H
    join -- join on the inserted and deleted tables to find out which HeadID's were affected.
        (select HeadID
        from inserted
        union
        select HeadID
        from deleted
        ) as C
        on C.HeadID = H.HeadID
end
go

答案 2 :(得分:0)

也许可以这样试试?

UPDATE Head h
SET h.Total_sum=(SELECT SUM(t.Amount) FROM Transaction t
               Where t.HeadID = t.HeadID
               GROUP BY t.HeadID)
WHERE h.ID= t.HeadID 

答案 3 :(得分:0)

你可以在不使用join的情况下实现它:

UPDATE tansaction_table
   SET Total_sum = (SELECT SUM(t2.Amount) 
                   FROM head_table t2 
                  WHERE t2.HeadID = ID)