更新整个表格从上一行添加值

时间:2017-07-25 14:57:34

标签: mysql sql

acc

This Is Table acc
如果我编辑“A”金额为100则总金额变更
整个表需要更新...
那么通过添加(信用)或从之前的总金额中减去(借记)来更新整个表的mysql查询是什么...

2 个答案:

答案 0 :(得分:0)

正如@Gordon Linoff评论的那样,您可以使用AFTER UPDATE触发器和循环来归档您的目标。我在下面写了这个想法,例如。

DELIMITER //

CREATE TRIGGER acc_after_update
AFTER UPDATE
   ON acc FOR EACH ROW

BEGIN

  DECLARE done INT DEFAULT FALSE;
  DECLARE type varchar(10);
  DECLARE total_amount DEFAULT 0;
  DECLARE name varchar(10)
  DECLARE amount INT;
  DECLARE cur1 CURSOR FOR SELECT name, type, amount FROM acc;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cur1;

  REPEAT
    FETCH cur1 INTO name, type, amount;

    IF NOT done THEN
      CASE type
        WHEN 'credit' THEN  = total_amount + amount;
        WHEN 'debit' THEN total_amount = total_amount - amount      
      END CASE
      UPDATE acc
        SET amount = total_amount
      WHERE name = @name --not sure about this syntax
    END IF;
  UNTIL done END REPEAT;

  CLOSE cur1;

END; //

DELIMITER ;

希望这有帮助。

答案 1 :(得分:0)

CREATE VIEW [dbo].[vSales]
AS
        SELECT ROW_NUMBER() OVER(ORDER BY s.[Name] ) AS 'RowNo', 
               s.* 
               , CASE WHEN Type = 'Credit' THEN Amount ELSE - 1 * Amount END As NewAmount
        FROM dbo.Sales AS s
GO

SELECT a.[RowNo], 
       a.[Name], 
       SUM(b.[NewAmount])  
FROM dbo.vSales AS a INNER JOIN dbo.vSales AS b ON a.[RowNo] >= b.[RowNo] 
GROUP BY a.[RowNo], a.[Name]

dbo.Sales是包含所有值的表