2017-02-01 47 views
1

在SQL Server中,我有两个表。第一个是如下:如何在SQL Server中交叉连接两个表,只重复一些值

id Value 
1 Green 
2 Yellow 
3 Red 

第二个是

id Value 
1 John 
2 Paul 
3 George 
4 Ringo 
5 Mick 
6 Keith 
7 Ronnie 

我如何加入这两个表,如结果数据集它如下:

id1 Value1 id2 Value2 
1 Green 1 John 
2 Yellow 2 Paul 
3 Red 3 George 
1 Green 4 Ringo 
2 Yellow 5 Mick 
3 Red 6 Keith 
1 Green 7 Ronnie 
+0

我改变在每个实施例表中的行的数目为奇数的行 – thx0125

回答

0

试试这个:

Select * 
From (Select 
    t.*, 
    2 - (Row_number() over (order by id) % 2) idx 
From second_table t) t inner join first_table t2 on t2.id = t.idx; 
0

您需要在where子句 中的一项声明表示table1.id%2 = table2.id%2

模运算符%将匹配第二个表的奇数值到绿色和偶数值到黄色。

+0

Thak你,伟大的答案;如果我在第一张桌子上有3排,第二张桌子上有7张? – thx0125

+0

@ thx0125:如果第一行中有3行,第二行中有7行,则使用%3而不是%2。第二个表中的前6行将与预期的第一个表匹配。第二个表中的第七行将与第一个表的第一行相匹配,这样就会有三次出现第一个表 - 第一行,而第一个表的第二和第三行只有两次出现。 –

0

下面是应该更新的版本问题的工作,一个样本:

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 | 
+----+--------+----+--------+