简体   繁体   English

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

[英]Update a column in a database table based on columns in another table

I have two tables 我有两张桌子

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   |

I want to update the balance column in table T1 as 我想将表T1中的余额列更新为

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

How can I do this in MS SQL server? 如何在MS SQL Server中执行此操作? Thanks! 谢谢!

I created temp table to recreate, so you can just use the update below: 我创建了临时表来重新创建,因此您可以使用以下更新:

 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

The below query can help you with updating all the rows for a particular column with a single query. 以下查询可以帮助您通过单个查询更新特定列的所有行。

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

Or you can also try this one 或者你也可以尝试这个

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM