如何使用SQL在同一列中生成排列?

时间:2017-01-04 05:02:55

标签: sql sql-server

我的表格如下所示:

LETTERS
--------    
A
B
C
D
E
F
G
H

我想创建一个视图,列出这些字母的所有3个字母组合,不再按以下方式重复,即为每个组合分配一个数字。

ViewNew
-------
1 A
1 B
1 C
2 A
2 B
2 D
3 A
3 B
3 E

等等。

以上可能吗?任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

对于排列(顺序很重要):

DECLARE @q as table([No] int, L1 char(1), L2 char(1), L3 char(1))

INSERT INTO @q
SELECT
    ROW_NUMBER() OVER (ORDER BY L1.Letter, L2.Letter, L3.Letter, L1.Letter), 
    L1.Letter, 
    L2.Letter, 
    L3.Letter
FROM
    Letters L1 CROSS JOIN
    Letters AS L2 CROSS JOIN
    Letters AS L3
WHERE
    (L1.Letter <> L2.Letter) AND 
    (L2.Letter <> L3.Letter) AND 
    (L1.Letter <> L3.Letter)

SELECT [No], L1 AS Letter FROM @q
UNION 
SELECT [No], L2 FROM @q
UNION
SELECT [No], L3 FROM @q

这实际上可以在单个查询中完成,但重复@q查询。 如果View是目标,我会将@q查询移动到子视图中。

<强>更新 使用UNPIVOT可以使事情变得更简单,就像Bhosale的答案中的pointed out一样。

答案 1 :(得分:1)

检查这个。使用Joins和UNPIVOT,我们可以找到所有字母的填充。

        select ID,ViewNew from 
        (
            select row_number() over(order by (select 1)) AS ID, 
            C2.LETTERS as '1' ,C1.LETTERS AS '2' ,c3.LETTERS as '3' from #tableName C1,#tableName c2,#tableName c3
            where C1.LETTERS != c2.LETTERS  and c2.LETTERS ! = c3.LETTERS and   c1.LETTERS ! = c3.LETTERS
        ) a  
        UNPIVOT
        (
          ViewNew
               FOR [LETTERS] IN ([1], [2], [3])
        )as f
  

OutPut:

enter image description here

答案 2 :(得分:-1)

如果要创建两个表之间所有唯一组合的列表,则只需要同时从两个表中进行选择,SQL Server将为您提供所需的内容。这称为CROSS JOIN

declare @t1 table (letter char(1))
declare @t2 table (number int)

insert @t1 values ('A'), ('B'), ('C')
insert @t2 values (1), (2), (3), (4)

select t2.number, t1.letter from @t1 as t1, @t2 as t2

结果

number  letter
--------------
1       A
1       B
1       C
2       A
2       B
2       C
3       A
3       B
3       C
4       A
4       B
4       C