基于另一个表中的列更新数据库表中的列

r7knjye2  于 2021-06-28  发布在  Hive
关注(0)|答案(2)|浏览(336)

我有两张table

T1
|id|balance|
|1| 1000  |
|2| 2000  | 
|3| 3000  |

T2
|id|rate|months|
|1|0.50| 10   |
|2|0.25| 24   |
|3|0.40| 16   |

我想将表t1中的balance列更新为

T1.Balance = T1.Balance + T2.rate*T2.months*T1.Balance

如何在ms sql server中执行此操作?谢谢!

9rbhqvlz

9rbhqvlz1#

我创建了要重新创建的临时表,因此您可以使用下面的更新:

CREATE TABLE #T1
 (id INT NOT NULL,
 balance money NOT NULL)

 INSERT INTO #T1
 (id,balance)
  VALUES 
 (1, 1000 ),
 (2, 2000 ) ,
 (3, 3000 )

 CREATE TABLE #T2
 (id INT NOT NULL,
 rate MONEY NOT NULL,
 months INT NOT NULL)

  INSERT #T2
 (id,rate,months)
  VALUES 
  (1,.5,10),
  (2,.25,24),
  (3,.4,16)

  --confirm data
  SELECT * FROM #T1
  SELECT * FROM #T2

  --update balances
   update t1 SET balance =  T1.Balance + (T2.rate*T2.months*T1.Balance)
   FROM #T1 AS t1 
     JOIN #T2 AS t2 
       ON t1.id = t2.id
avwztpqn

avwztpqn2#

下面的查询可以帮助您使用单个查询更新特定列的所有行。

UPDATE T1 AS t1 SET t1.balance = t1.balance * (SELECT t2.rate * t2.months FROM T2 AS t2 WHERE t2.id = t1.id);

或者你也可以试试这个

UPDATE T1 AS t SET t.balance = (t1.balance * t2.rate * t2.months) FROM T1 AS t1 JOIN T2 AS t2 ON t1.id = t2.id;

相关问题