在SQL Server 2012中,我有两个表:
Table A
1
2
3
Table B
A
B
C
D
E
F
是否有简单的(不使用游标)方式选择:
1, A
1, B
2, C
2, D
3, E
3, F
答案 0 :(得分:0)
我的尝试是不要尝试任何太花哨的东西。它是这样的:
SET @maxcounter = (SELECT MAX(ID) FROM @TableA)
SET @counter = 1
WHILE(@counter <= @maxcounter)
BEGIN
SELECT
(SELECT Company_ID FROM @TableA WHERE ID = @counter),
(SELECT Person_ID FROM @TableB WHERE ID = (@counter * 2) - 1)
SELECT
(SELECT Company_ID FROM @TableA WHERE ID = @counter),
(SELECT Person_ID FROM @TableB WHERE ID = (@counter * 2))
SET @counter = @counter + 1
END
maxcounter和counter是int变量。 TableA和TableB是表变量,并且都具有ID标识字段。它并不优雅,但它可以满足我的需求。
这不会投入生产 - 它只是在脚本中用于使用测试数据填充表。
答案 1 :(得分:0)
另一种解决方案(不是我的,但更好/更简单)是:
DECLARE @TotalTableA INT
SET @TotalTableA = (SELECT COUNT(Company_ID) FROM @TableA AS c)
;WITH cte1 AS (
SELECT Company_ID, ROW_NUMBER() OVER (ORDER BY Company_ID) AS row_num
FROM @TableA AS c
),cte2 (Person_ID, row_num) as
(
SELECT Person_ID, (Person_ID % @TotalTableA) + 1 AS row_num
FROM @TableB
)
SELECT Company_ID,Person_ID FROM cte1 JOIN cte2 ON cte2.row_num = cte1.row_num
这可以避免计数器,也不需要ID字段。稍微不同的是我的第一个想法是严格关于TableB的两行。此答案试图在TableA中平均分割TableB中的所有行。