如何通过SQL输出此数字列表?

时间:2015-12-18 17:41:34

标签: sql sql-server algorithm

我在SQL DB中有一个数字列表,如下所示:

N1 | N2 | N3 | N4 | N5
----------------------
1  |  2 |  3 |  4 |  5

如何找出此列表的所有可能组合并通过查询输出?

我看了this,我不知道从哪里开始。

2 个答案:

答案 0 :(得分:2)

使用交叉联接:

DECLARE @id INT = 1;

WITH cte
AS (
      SELECT N1 AS c FROM #tab WHERE id = @id
      UNION ALL 
      SELECT N2 FROM #tab WHERE id = @id
      UNION ALL 
      SELECT N3 FROM #tab WHERE id = @id
      UNION ALL 
      SELECT N4 FROM #tab WHERE id = @id
      UNION ALL 
      SELECT N5 FROM #tab WHERE id = @id
)
SELECT *, CONCAT(c1.c, c2.c, c3.c, c4.c, c5.c) AS combined
FROM cte c1,cte c2,cte c3,cte c4,cte c5

LiveDemo

我假设你的桌号有某种主键。

编辑:

不是最漂亮的解决方案来获取不同值的排列但应该有效:

WITH cte AS 
(
      SELECT N1 AS c FROM #tab WHERE id = @id
      UNION ALL 
      SELECT N2 FROM #tab WHERE id = @id
      UNION ALL 
      SELECT N3 FROM #tab WHERE id = @id
      UNION ALL 
      SELECT N4 FROM #tab WHERE id = @id
      UNION ALL 
      SELECT N5 FROM #tab WHERE id = @id
),cte2 AS 
(      
  SELECT CONCAT(c1.c, c2.c, c3.c, c4.c, c5.c) AS combined
  FROM cte c1,cte c2,cte c3,cte c4,cte c5
)
SELECT cte2.combined
FROM cte2
JOIN #tab t
  ON CHARINDEX(CAST(t.N1 AS CHAR(1)), cte2.combined) > 0
 AND CHARINDEX(CAST(t.N2 AS CHAR(1)), cte2.combined) > 0
 AND CHARINDEX(CAST(t.N3 AS CHAR(1)), cte2.combined) > 0
 AND CHARINDEX(CAST(t.N4 AS CHAR(1)), cte2.combined) > 0
 AND CHARINDEX(CAST(t.N5 AS CHAR(1)), cte2.combined) > 0
 AND t.id = @id;

LiveDemo2

获得排列的最简洁方法可能是使用递归CTE。

答案 1 :(得分:1)

CREATE TABLE [dbo].[numberstable](
    [n1] [int] NULL,
    [n2] [int] NULL,
    [n3] [int] NULL,
    [n4] [int] NULL,
    [n5] [int] NULL
) ON [PRIMARY]
go
insert into numberstable values (1,2,3,4,5)
go
WITH range
AS (
SELECT N1 AS c FROM numberstable
      UNION  
      SELECT N2 FROM numberstable
      UNION  
      SELECT N3 FROM numberstable
      UNION  
      SELECT N4 FROM numberstable
      UNION  
      SELECT N5 FROM numberstable)
SELECT *
FROM range r1,range r2,range r3,range r4,range r5
    where r1.c <> r2.c and r1.c<>r3.c and r1.c<>r4.c and r1.c<>r5.c
    and r2.c <> r3.c and r2.c<>r4.c and r2.c<>r5.c
    and r3.c<>r4.c and r3.c<>r5.c
    and r4.c <> r5.c
order by r1.c, r2.c, r3.c, r4.c, r5.c
go
drop table numberstable
go