下面是应该更新的版本问题的工作,一个样本:
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