如何在SQL Server中交叉连接两个表,只重复一些值

时间:2017-02-01 19:31:33

标签: sql-server join

在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

3 个答案:

答案 0 :(得分:0)

您需要在where子句中使用语句 说table1.id%2 = table2.id%2

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

答案 1 :(得分: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;

答案 2 :(得分: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 |
+----+--------+----+--------+