我有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')
有什么建议吗?
答案 0 :(得分:1)
您需要在子查询中使用GROUP BY
,然后相应地JOIN
使用其他表格。像这样:
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