下面是應該更新的版本問題的工作,一個樣本:
declare @colors table (
id int not null,
value nvarchar(15) not null
)
declare @people table (
id int not null,
name nvarchar(15) not null
)
insert into @colors (id, value) values (1, 'Green'),(2,'Yellow'),(3,'Red')
insert into @people (id, name) values (1, 'John'),(2,'Paul'),(3,'George'),(4,'Ringo'),(5,'Mick'),(6,'Keith'),(7,'Ronnie')
----
select csub.id, csub.value, psub.id, psub.name
from
(
select id, name,
(row_number() over (order by id)) % (select count(*) from @colors) as rnum
from @people
) as psub
join (
select id, value,
((row_number() over (order by id)) % (select count(*) from @colors)) as rnum
from @colors
) csub on psub.rnum = csub.rnum
order by psub.id
注:這也適用,即使實際ID值在兩個表有差距。像:
insert into @colors (id, value) values (1, 'Green'),(17,'Yellow'),(33,'Red'),(47,'Black)
insert into @people (id, name) values (1, 'John'),(2,'Paul'),(3,'George'),(7,'Ringo'),(15,'Mick'),(16,'Keith'),(37,'Ronnie')
和它的作品,無論你有多少行有顏色表。輸出使用上述樣品,在ID的間隙的範圍內:
+----+--------+----+--------+
| id | value | id | name |
+----+--------+----+--------+
| 1 | Green | 1 | John |
| 17 | Yellow | 2 | Paul |
| 33 | Red | 3 | George |
| 47 | Black | 7 | Ringo |
| 1 | Green | 15 | Mick |
| 17 | Yellow | 16 | Keith |
| 33 | Red | 37 | Ronnie |
+----+--------+----+--------+
我改變在每個實施例表中的行的數目爲奇數的行 – thx0125