加入和重复行

tec*_*der 4 sql sql-server sql-server-2008

我需要为其他表中的值重复行.例如:

Order table
Order
1
2
3
4
5
6

Dept table

Dept    Person
A   P1
A   P2
B   P3
B   P4
B   P5
C   P6
C   P7
C   P8
C   P9

Output expected
Dept    Person  Order
A   P1  1
A   P2  2
A   P1  3
A   P2  4
A   P1  5
A   P2  6
B   P3  1
B   P4  2
B   P5  3
B   P3  4
B   P4  5
B   P5  6
C   P6  1
C   P7  2
C   P8  3
C   P9  4
C   P6  5
C   P7  6
Run Code Online (Sandbox Code Playgroud)

关于如何做到这一点的任何想法?我为了简单而保持秩序,但它不需要按顺序排列; 假设它是日期或varchar!

Gio*_*sos 6

这是一种方法:

SELECT Dept, Person, [Order]
FROM (SELECT Dept, Person,
            ROW_NUMBER() OVER (PARTITION BY Dept 
                               ORDER BY Person) AS rn,
            COUNT(*) OVER (PARTITION BY Dept) AS cnt
      FROM Dept ) t                            
CROSS JOIN [Order]
WHERE rn = ([Order] - 1) % cnt + 1
ORDER BY Dept, [Order], Person
Run Code Online (Sandbox Code Playgroud)

这是一种强力解决方案:您获得表和表之间的每一个组合Order,Dept并使用窗口函数有选择地从这个笛卡尔集中过滤行.

在这里演示

编辑:(信用到@Giorgi)

通过简单的方法可以实现相同的结果JOIN:

SELECT Dept, Person, [Order]
FROM (SELECT Dept, Person,
            ROW_NUMBER() OVER (PARTITION BY Dept 
                               ORDER BY Person) AS rn,
            COUNT(*) OVER (PARTITION BY Dept) AS cnt
      FROM Dept ) t                            
INNER JOIN [Order] ON rn = ([Order] - 1) % cnt + 1
ORDER BY Dept, [Order], Person
Run Code Online (Sandbox Code Playgroud)

后一种解决方案肯定更有效.

在这里演示

  • @ user2169261,只需添加额外的cte,您将按日期排序您的订单,无论如何,您将获得1,2,3,4,5,6 (2认同)
  • @GiorgosBetsos,而不是`cross join`你可以加入:`JOIN [Order] on rn =([Order] - 1)%cnt + 1` (2认同)