我有一个 SQL Server DB,其中包含列 NM1-NM69 及其字段值中的相应数字:
NM1 | NM2 | NM3 | NM4 | NM5 |...... | NM69 ------------------------------------------ 1 | 2 | 3 | 4 | 5 |...... | 69
我试图找出这个列表的所有 5 个数字排列。我如何以简单易行(好..更容易)的方式做到这一点?
示例输出:
PM NM1 | PM NM2 | PM NM3 | PM NM4 | PM NM5 | -------------------------------------------- 68 | 2 | 55 | 43 | 52 |
编辑:我正在使用 SQL
您将数据 UNPIVOT 放入一列,然后 CROSS JOIN 五次。这是一个 SQL Fiddle 排列 5 列选择 3. SQL Fiddle
3. SQL Fiddle
DECLARE @t TABLE (Field1 INT, Field2 INT, Field3 INT, Field4 INT, Field5 INT) INSERT INTO @t VALUES (1,2,3,4,5) ; WITH cte AS ( SELECT u.FieldValue FROM @t UNPIVOT ( [FieldValue] FOR [FieldName] IN ( Field1, Field2, Field3, Field4, Field5 ) ) u ) SELECT t1.FieldValue AS PermuteField1, t2.FieldValue AS PermuteField2, t3.FieldValue AS PermuteField3 FROM cte AS t1 CROSS JOIN cte AS t2 CROSS JOIN cte AS t3 WHERE t1.FieldValue <> t2.FieldValue AND t1.FieldValue <> t3.FieldValue AND t2.FieldValue <> t3.FieldValue