连接两个表中的记录

时间:2020-12-18 14:20:37

I want to do a query to return something like this

我想做一个查询来返回这样的东西

Table 1
Id1    Name
  1    A
  2    B
  3    C
  4    D
  5    E   

 Table 2
    Id2
    10
    11
    12

I need to go to table2 and return each record in Table1 like this:

我需要到表2,返回表1中的每条记录,如下所示:

Id1 Name Id2
1    A   10
2    B   11
3    C   12
4    D   10
5    E   11

When I finish the records in Table2, I start again until completing the records in Table1 Thanks!

当我完成表2中的记录后,我重新开始,直到完成表1中的记录,谢谢!

1 个解决方案

#1


0  

Try with this query, this works perfectly (here is the link for you to try)

尝试使用这个查询,效果非常好(以下是要尝试的链接)

WITH tempTable1 AS
(
    SELECT
        b.ID2,
        ROW_NUMBER() OVER (ORDER BY ID2) AS position1
    FROM
        TABLE2 b
)
SELECT x.ID1, x.NAME, isnull((SELECT b.id2 FROM tempTable1 b WHERE b.position1 = (x.position2 % (SELECT COUNT(1) FROM tempTable1))),
(SELECT TOP 1 y.id2 FROM tempTable1 y ORDER BY y.position1 desc)) AS ID2
FROM (
SELECT A.ID1, A.NAME, ROW_NUMBER() OVER (ORDER BY A.ID1) AS position2
FROM TABLE1 A
) X

This query I do not like it, but I could not make another :(

这个问题我不喜欢,但我不能再做一个:

#1


0  

Try with this query, this works perfectly (here is the link for you to try)

尝试使用这个查询,效果非常好(以下是要尝试的链接)

WITH tempTable1 AS
(
    SELECT
        b.ID2,
        ROW_NUMBER() OVER (ORDER BY ID2) AS position1
    FROM
        TABLE2 b
)
SELECT x.ID1, x.NAME, isnull((SELECT b.id2 FROM tempTable1 b WHERE b.position1 = (x.position2 % (SELECT COUNT(1) FROM tempTable1))),
(SELECT TOP 1 y.id2 FROM tempTable1 y ORDER BY y.position1 desc)) AS ID2
FROM (
SELECT A.ID1, A.NAME, ROW_NUMBER() OVER (ORDER BY A.ID1) AS position2
FROM TABLE1 A
) X

This query I do not like it, but I could not make another :(

这个问题我不喜欢,但我不能再做一个: