注意:在澄清 tableb
的行数少于 table后,我更改了此答案a
。
这可以通过MERGE
.
首先,假设表a
中的行具有以下a1
值:1, 1, 1, 1, 2, 2, 2, 2, 7, 7, 10, 10, 10, 10, 12, 12, 13, 13, 13, 13, 15, 15
.
接下来,假设表b
具有具有以下b2
值的行:102, 103, 104, 105, 106, 107, 108
.
使用此查询,每个a1
值都可以与b2
值轮流配对:
SELECT * FROM
(SELECT a1, ROW_NUMBER() OVER (PARTITION BY a1 ORDER BY NULL) AS RowA
FROM a) TableA
INNER JOIN
(SELECT b2, ROW_NUMBER() OVER (Order by b2) AS RowB
FROM b) TableB
ON Tablea.RowA = TableB.RowB
A1 ROWA B2 ROWB
--- ---- --- ----
1 1 102 1 <-- first a1=1 goes with b2=102
1 2 103 2 <-- second a1=1 goes with b2=103
1 3 104 3 <-- third a1=1 goes with b2=104
1 4 105 4 <-- fourth a1=1 goes with b2=105
2 1 102 1 <-- start again: first a1=2 goes with b2=102
2 2 103 2 <-- and so on...
2 3 104 3
2 4 105 4
7 1 102 1
7 2 103 2
10 1 102 1
10 2 103 2
10 3 104 3
10 4 105 4
12 1 102 1
12 2 103 2
13 1 102 1
13 2 103 2
13 3 104 3
13 4 105 4
15 1 102 1
15 2 103 2
这对于合并来说是不够的,因为它不能a
唯一地标识表行,但ROWID
可以解决这个问题。这是完整的查询:
MERGE INTO a
USING (
SELECT * FROM
(SELECT
a.ROWID as ID,
a1,
ROW_NUMBER() OVER (PARTITION BY a1 ORDER BY a2) AS RowA
FROM a) TableA
INNER JOIN
(SELECT b2, ROW_NUMBER() OVER (Order by b2) AS RowB
FROM b) TableB
ON Tablea.RowA = TableB.RowB) AtoB
ON (a.ROWID = AtoB.ID)
WHEN MATCHED THEN UPDATE SET a.a2 = AtoB.b2
这是a
更新后的表格:
SELECT a1, a2 FROM a ORDER BY a1, a2;
A1 A2
--- ----
1 102
1 103
1 104
1 105
2 102
2 103
2 104
2 105
7 102
7 103
10 102
10 103
10 104
10 105
12 102
12 103
13 102
13 103
13 104
13 105
15 102
15 103