0

抱歉,如果这个问题之前已经回答过。我打猎,但找不到任何东西。

问题:

我正在使用 SQL Server 2012,我有两个表(TableATableB),如下所示

表 A

+-------+--------+
| ItemA | SeqNoA |
+-------+--------+
| D     |      1 |
| A     |      0 |
| Z     |      0 |
| B     |      4 |
| A     |      0 |
| K     |      6 |
+-------+--------+

表B

+-------+--------+
| ItemB | SeqNoB |
+-------+--------+
| A     |      1 |
| D     |      2 |
| C     |      3 |
| A     |      4 |
| B     |      5 |
| J     |      6 |
+-------+--------+

TableAcol 的某些行中缺少(零)值SeqNo,而在 col 中存在相同的SeqNoTableB。我需要找到某种方法来加入这些表,以便最终得到以下给定值。这个连接既可以是某种连接查询,也可以是基于这两个表创建一个全新的表

+-------+--------+-------+
| ItemA | SeqNoA | ItemB |
+-------+--------+-------+
| D     |      1 | A     |
| A     |      2 | D     |
| Z     |      3 | C     |
| B     |      4 | A     |
| A     |      5 | B     |
| K     |      6 | J     |
+-------+--------+-------+
4

2 回答 2

1

Missing values in column SeqNoA has value 0. In case you don't have a primary key in your table you can write a query as below by assigning each row a unique sequence number in TableA:

select TA.ItemA , TA.NewSeqNoA as SeqNoA , TB.ItemB 
from 
(
select ItemA, SeqNoA , ROW_NUMBER() over (order by (select 1)) as NewSeqNoA
from tableA ) TA
join tableB TB on TA.NewSeqNoA = TB.SeqNoB 

but if you have a primary key in tableA then you can modify this query something like below to give you correct row number:

select TA.ItemA , TA.NewSeqNoA as SeqNoA , TB.ItemB 
from 
(
select ItemA, SeqNoA , ROW_NUMBER() over (order by ('TableA PK')) as NewSeqNoA
from tableA ) TA
join tableB TB on TA.NewSeqNoA = TB.SeqNoB 
于 2013-11-01T07:06:53.940 回答
0
ON tableB.SeqNo = ISNULL(tableA.SeqNo,tableB.SeqNo)
于 2013-11-01T06:19:55.503 回答