怎么写sql查询?对于ms sql server

时间:2021-04-12 15:41:20

I need to write a sql query that adds one column from one database (DB1) to another column and the sum is save in that column in the second database(DB2). where userIds are the same

我需要编写一个sql查询,将一个数据库(DB1)中的一列添加到另一列,并将总和保存在第二个数据库(DB2)的该列中。其中userIds是相同的

DB1
TableA
UserId People


DB2
TableB
Amount UserId

it would be something like this

它会是这样的

DB2.TableB.Amount = DB2.TableB.Amount + DB1.TableA.People

DB2.TableB.Amount = DB2.TableB.Amount + DB1.TableA.People

3 个解决方案

#1


Do you mean:

你的意思是:

UPDATE b
SET    Amount = b.Amount + a.People
FROM DB2.dbo.TableB b
INNER JOIN DB1.dbo.TableA a
  ON  a.UserId = b.UserId

dbo = owner of table, it can also be unspecified: DB1..TableA

dbo =表的所有者,它也可以是未指定的:DB1..TableA

#2


INSERT INTO DB2.dbo.TableB
SELECT COUNT(*), UserID
FROM DB1.dbo.TableA
GROUP BY UserID

#3


This is untested:

这是未经测试的:

INSERT INTO DB2.dbo.TableB
SELECT SUM(DB2.TableB.Amount + DB1.TableA.People), UserID
FROM DB1.dbo.TableA
GROUP BY UserID

#1


Do you mean:

你的意思是:

UPDATE b
SET    Amount = b.Amount + a.People
FROM DB2.dbo.TableB b
INNER JOIN DB1.dbo.TableA a
  ON  a.UserId = b.UserId

dbo = owner of table, it can also be unspecified: DB1..TableA

dbo =表的所有者,它也可以是未指定的:DB1..TableA

#2


INSERT INTO DB2.dbo.TableB
SELECT COUNT(*), UserID
FROM DB1.dbo.TableA
GROUP BY UserID

#3


This is untested:

这是未经测试的:

INSERT INTO DB2.dbo.TableB
SELECT SUM(DB2.TableB.Amount + DB1.TableA.People), UserID
FROM DB1.dbo.TableA
GROUP BY UserID