在Sql server中查询以下模式

时间:2018-05-03 09:43:20

标签: sql sql-server

我正在尝试实现底部显示的输出,但是不知道如何才能完成。

#T1#T2是输入表。

CREATE TABLE #T1
(ID VARCHAR(10))
INSERT INTO #T1
SELECT 'A'
UNION 
SELECT 'B'
UNION
SELECT 'C'
CREATE TABLE #T2
(ID VARCHAR(10))
INSERT INTO #T2
SELECT 1
UNION 
SELECT 2
UNION
SELECT 3
UNION
SELECT 4
UNION 
SELECT 5
UNION
SELECT 6
UNION
SELECT 7

使用#T1#T2的预期输出是

OUTPUT 
ID ID
A  1
B  2
C  3
A  4
B  5
C  6
A  7

4 个答案:

答案 0 :(得分:4)

然而,它并不是特别漂亮:

WITH T1 AS(
    SELECT ID,
           ROW_NUMBER() OVER (ORDER BY ID) AS RN
    FROM #T1),
T1M AS(
    SELECT *, MAX(RN) OVER () AS MAXRN
    FROM T1),
T2 AS(
    SELECT ID,
           ROW_NUMBER() OVER (ORDER BY ID) AS RN
    FROM #T2)

SELECT T1.ID AS T1ID,
       T2.ID AS T2ID
FROM T1M T1
     JOIN T2 ON T1.RN = CASE T2.RN % T1.MAXRN WHEN 0 THEN T1.MAXRN ELSE T2.RN % T1.MAXRN END
ORDER BY T2.ID ASC;

编辑:注意,这假设T1的行数少于T2。如果反之亦然,那就不行了。

答案 1 :(得分:2)

您可以使用CTE

with t1 as (
    select *, 
           ROW_NUMBER() over (order by id) Seq 
    from #t1
), t2 as (
    select *, 
           1+(ROW_NUMBER() over (order by id)-1) % (select COUNT(1) from t1) Seq
    from #t2
) 
select t1.Id, t2.Id
from t2
inner join t1 on t1.Seq = t2.Seq
order by t2.Id;

答案 2 :(得分:2)

尝试这个,在行编号和分组中有点长的过程,但几乎就是所有的过程,加上行号和分组,非常简单

with cte as (
    SELECT ID, ceiling(cast(row_number() over
    (order by ID ASC) as decimal)/ 3) as grp FROM #T2
)
SELECT T1.ID, T2.ID FROM 
(SELECT ID, cast(row_number() over
                   (order by ID ASC) as decimal) as grp FROM #T1) T1
LEFT JOIN
(SELECT ID, cast(row_number() over
                   (PARTITION BY grp order by ID ASC) as decimal) as grp FROM cte) T2
ON T1.grp = T2.grp
ORDER BY T2.ID

结果如下

enter image description here

答案 3 :(得分:1)

SQL小提琴:http://sqlfiddle.com/#!18/03a3f/39

SELECT
  T1.ID
  , T2.ID
FROM
  (SELECT
     ROW_NUMBER() OVER (ORDER BY ID ASC) AS ROW_NUM
   , T2.ID FROM T2
  ) AS T2
  INNER JOIN
    (SELECT ROW_NUMBER() OVER (ORDER BY ID ASC) AS ROW_NUM
     , (SELECT COUNT(*) FROM T1) AS SEQ_COUNT
     , T1.ID FROM T1
    ) AS T1 ON
      T1.ROW_NUM =
        CASE (T2.ROW_NUM % T1.SEQ_COUNT)
          WHEN 0 THEN T1.SEQ_COUNT
          ELSE (T2.ROW_NUM % T1.SEQ_COUNT)
        END
ORDER BY
  T2.ROW_NUM ASC;

结果:

+----+----+
| ID | ID |
+----+----+
| A  |  1 |
| B  |  2 |
| C  |  3 |
| A  |  4 |
| B  |  5 |
| C  |  6 |
| A  |  7 |
+----+----+