SQL-计数记录并将结果插入到另一个表中

SQL-计数记录并将结果插入到另一个表中,sql,Sql,我有3个数据库 DB1 - I need to count the rows in Table2.column1 by RefNum from DB3 DB2 - Use the count from DB1 to update List table, QtyAdd column DB3 - contains a RefNum that both DB1 and DB2 use. 下面的查询将从DB1进行计数,并更新DB2中的QtyAdd列。 我不知道如何使用来自DB3的RefNum来添加到S

我有3个数据库

DB1 - I need to count the rows in Table2.column1 by RefNum from DB3
DB2 - Use the count from DB1 to update List table, QtyAdd column
DB3 - contains a RefNum that both DB1 and DB2 use.
下面的查询将从DB1进行计数,并更新DB2中的QtyAdd列。 我不知道如何使用来自DB3的RefNum来添加到SELECT语句和UPDATE部分

UPDATE List
SET QtyAdd = i.QTY
FROM (Select COUNT (Column1) AS QTY FROM DB2.dbo.Table2 WHERE (Column1 LIKE 'A%') and (RefNum = '2833')) i
WHERE (RefNum = '2833')

//Works but the RefNum is manually put in
//I have tried the following with no luck:

UPDATE List
SET QtyAdd = i.QTY
FROM (Select COUNT (Column1) AS QTY FROM DB2.dbo.Table2 WHERE (Column1 LIKE 'A%') and (RefNum = DB3.dbo.Ref.Refnum)) i
WHERE (RefNum = DB3.dbo.Ref.Refnum')

有什么建议吗?

您需要在子查询中使用
分组依据
,然后
相应地将
加入到其他表中。大概是这样的:

UPDATE L
SET QtyAdd = i.QTY
FROM List L JOIN 
    (SELECT RefNum, COUNT(Column1) AS QTY 
     FROM DB2.dbo.Table2 
     WHERE Column1 LIKE 'A%'
     GROUP BY RefNum) i ON L.RefNum = i.RefNum JOIN 
    DB3.dbo.Ref r ON l.RefNum = r.RefNum