我创建了一个表格,可以完成字母表的所有3个字母组合。见下文
ID 1stLetter 2ndLetter 3rdLetter
1 A B C
2 A B D
3 A B E
and so on
我有第二张表如下:
Letter Number
A 0
A 1
B 0
B 1
C 0
D 0
D 1
E 0
E 1
E 2
我一直试图找出如何将两者结合起来,以便第一个表的每一行与第二个表组合以获得所有可能的组合。例如,输出应如下所示:
NEWID ID 1stLetter 2ndLetter 3rdLetter 1stNumber 2ndNumber 3rd Number
1 1 A B C 0 0 0
2 1 A B C 1 0 0
3 1 A B C 0 1 0
4 1 A B C 1 1 0
5 2 A B D 0 0 0
6 2 A B D 0 0 1
7 2 A B D 0 1 0
8 2 A B D 0 0 1
9 2 A B D 1 0 0
10 2 A B D 1 0 1
11 2 A B D 1 1 0
12 2 A B D 1 0 1
13 2 A B D 1 1 1
14 3 A B E and so on
这可能吗?任何帮助将不胜感激。
谢谢,
Ĵ
答案 0 :(得分:2)
这应该可以解决问题,希望代码是自我解释的,如果不是,请询问:
CREATE TABLE #combo
(
id INT ,
letter1 NVARCHAR(1) ,
letter2 NVARCHAR(1) ,
letter3 NVARCHAR(1)
);
CREATE TABLE #numbers
(
letter NVARCHAR(1) ,
number INT
);
INSERT INTO #combo
( id, letter1, letter2, letter3 )
VALUES ( 1, 'A', 'B', 'C' ),
( 2, 'A', 'B', 'D' ),
( 3, 'A', 'B', 'E' );
INSERT INTO #numbers
( letter, number )
VALUES ( 'A', 0 ),
( 'A', 1 ),
( 'B', 0 ),
( 'B', 1 ),
( 'C', 0 ),
( 'C', 1 ),
( 'D', 0 ),
( 'D', 1 ),
( 'E', 0 ),
( 'E', 1 ),
( 'E', 2 );
SELECT c.* ,
n1.number ,
n2.number ,
n3.number
FROM #combo c
INNER JOIN #numbers n1 ON c.letter1 = n1.letter
INNER JOIN #numbers n2 ON c.letter2 = n2.letter
INNER JOIN #numbers n3 ON c.letter3 = n3.letter
ORDER BY id;
DROP TABLE #combo;
DROP TABLE #numbers;
答案 1 :(得分:-1)
使用CROSS JOIN
SELECT * FROM [data source1] CROSS JOIN [data source2]