SQL Server:根据第二个表中的ID更新包含来自同一个表的值的表

时间:2014-04-17 16:19:52

标签: sql sql-server sql-server-2008 tsql

我有一个名为STOCK的表,我想要更新它,如下所示:

-------------------------
NUMBER           | UNITS
-------------------------
NA13ALPK1010     |  9
NA13ALANA1010    | 11
NA13ALPK1065     |  4
NA13ALANA106     |  5
ON0003    XS     |  1
AT3322    2      |  3

基于名为PKGINV的第二个表,如下所示:

----------------------------------------
PKGNUMBER        | BOARDNUMBER
----------------------------------------
NA13ALPK1010   | NA13ALANA1010
NA13ALPK1065   | NA13ALANA106

首先,我希望能够使用某种类型的联接进行SELECT,以便我可以UNITS显示STOCK PKGNUMBERBOARDNUMBERPKGINV中{1}}。

然后,我想UNITS使用STOCK PKGINV.PKGNUMBER = STOCK.NUMBER PKGINV.BOARDNUMBER UNITS更新STOCK {/ 1}}。

因此,在更新后,NA13ALPK1010UNITS 11(来自UNITS的{​​{1}})NA13ALANA1010NA13ALPK1065 UNITS 1 {}} 5(来自UNITS的{​​{1}})。

先谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

您的SELECT只需加入STOCK表两次:

SELECT 
PKGNUMBER_Stock.UNITS AS PKGNUMBER_UNITS
,BOARDNUMBER_Stock.UNITS AS BOARDNUMBER_UNITS
FROM 
PKGINV AS pkginv
JOIN STOCK AS PKGNUMBER_Stock ON PKGNUMBER_Stock.NUMBER = pkginv.PKGNUMBER
JOIN STOCK AS BOARDNUMBER_Stock ON BOARDNUMBER_Stock.NUMBER = pkginv.BOARDNUMBER

同样,UPDATE语句应该只匹配上面的连接集:

UPDATE PKGNUMBER_Stock
SET PKGNUMBER_Stock.UNITS = BOARDNUMBER_Stock.UNITS
FROM 
PKGINV AS pkginv
JOIN STOCK AS PKGNUMBER_Stock ON PKGNUMBER_Stock.NUMBER = pkginv.PKGNUMBER
JOIN STOCK AS BOARDNUMBER_Stock ON BOARDNUMBER_Stock.NUMBER = pkginv.BOARDNUMBER

答案 1 :(得分:0)

您需要将Stock加入PKGINV两次:

Update s
set s.UNITS = s2.UNITS 
from STOCK s
join PKGINV p on s.NUMBER = p.PKGNUMBER
join STOCK s2 on p.BOARDNUMBER = s2.NUMBER