如何生成排列?

时间:2016-05-26 07:05:34

标签: sql sql-server

我有n个(例如3个)表,有一些这样的数据:

A: a1, a2, a3
----------------- 
B: b1, b2
----------------- 
C: c1, c2

我希望在SQL Server中生成这些数据的所有组合。像这样:

a1,b1,c1
a1,b1,c2
a1,b2,c1
a1,b2,c2
a2,b1,c1
.
.
.

祝你好运。请帮帮我!

2 个答案:

答案 0 :(得分:2)

这是CROSS JOIN的用途:

SELECT A.*, B.*, C.*
FROM A
CROSS JOIN B
CROSS JOIN C

答案 1 :(得分:0)

在做了一些可能是讽刺的评论之后,整个晚上这个问题都停留在我的大脑中,我最终提出了以下基于集合的方法。我相信它绝对有资格作为“优雅”,但后来我也认为它有资格作为“有点愚蠢”。你打电话。

首先,设置一些表格:

--  For testing purposes
DROP TABLE Source
DROP TABLE Numbers
DROP TABLE Results

--  Add as many rows as need be processed--though note that you get N! (number of rows, factorial) results,
--  and that gets big fast. The Identity column must start at 1, or the algorithm will have to be adjusted.
--  Element could be more than char(1), though the algorithm would have to be adjusted again, and each element
--  must be the same length.
CREATE TABLE Source
 (
   SourceId  int      not null  identity(1,1)
  ,Element   char(1)  not null
 )

INSERT Source (Element) values ('A')
INSERT Source (Element) values ('B')
INSERT Source (Element) values ('C')
INSERT Source (Element) values ('D')
--INSERT Source (Element) values ('E')
--INSERT Source (Element) values ('F')


--  This is a standard Tally table (or "table of numbers")
--  It only needs to be as long as there are elements in table Source
CREATE TABLE Numbers (Number int not null)
INSERT Numbers (Number) values (1)
INSERT Numbers (Number) values (2)
INSERT Numbers (Number) values (3)
INSERT Numbers (Number) values (4)
INSERT Numbers (Number) values (5)
INSERT Numbers (Number) values (6)
INSERT Numbers (Number) values (7)
INSERT Numbers (Number) values (8)
INSERT Numbers (Number) values (9)
INSERT Numbers (Number) values (10)


--  Results are iteratively built here. This could be a temp table. An index on "Length" might make runs
--  faster for large sets.  Combo must be at least as long as there are characters to be permuted.
CREATE TABLE Results
 (
   Combo   varchar(10)  not null
  ,Length  int          not null
 )