t-sql k值,n个位置的组合

时间:2017-11-07 05:39:31

标签: sql-server tsql

t-sql k值的组合,n个位置:

K Values
'A', 'B'

N Positions -- can be any value

Result if N = 2:
'A', 'A'
'A', 'B'
'B', 'A'
'B', 'B'    

Result if N = 3:
'A', 'A', 'A'
'A', 'A', 'B'
'A', 'B', 'A'
'A', 'B', 'B'
'B', 'A', 'A'
'B', 'A', 'B'
'B', 'B', 'A'
'B', 'B', 'B'

我认为必须对自己进行n - 1 CROSS JOIN,即使用动态t-sql吗?

即。当N = 2

WITH CTEValues(Value) AS (
    SELECT 'A' UNION SELECT 'B'
)
SELECT c1.Value AS A, C2.Value AS B
FROM CTEValues c1
CROSS JOIN CTEValues c2
ORDER BY c1.Value, c2.Value

或3

WITH CTEValues(Value) AS (
    SELECT 'A' UNION SELECT 'B'
)
SELECT c1.Value AS A, C2.Value AS B, C3.Value
FROM CTEValues c1
CROSS JOIN CTEValues c2
CROSS JOIN CTEValues c3
ORDER BY c1.Value, c2.Value, c3.Value

除非没有使用unpivot然后转动?

2 个答案:

答案 0 :(得分:3)

如果您正在寻找RBAR and dynamic Sql

如果您无法在原始要求中实施相同内容,请与我们联系。

同时测试其他样本数据。

CREATE TABLE #Table ( Value VARCHAR(10))
INSERT INTO #Table VALUES ('A'),('B')

DECLARE @N INT=3
declare @i int=1
declare @c varchar(10)='C'
DECLARE @Sql VARCHAR(max)=''
DECLARE @Col VARCHAR(max)=''
DECLARE @CrossSql VARCHAR(max)=''
DECLARE @OrderBy VARCHAR(max)=' ORDER BY c.Value '

WHILE (@i<@N)
begin
set @Col=@Col+', c'+cast(@i as varchar)+'.Value '
SET @CrossSql=@CrossSql+' CROSS JOIN #Table c'+cast(@i as varchar)
set @OrderBy=@OrderBy+', c'+cast(@i as varchar)+'.Value '

set @i=@i+1
end
--print @ExtraSql
set @Sql='SELECT c.Value AS A'+@Col+
' FROM #Table c'
+@CrossSql
+@OrderBy

print @Sql
EXEC(@Sql)

drop table #Table

答案 1 :(得分:1)

这是使用动态T-SQL语句的完整工作示例。我在临时表中保存K值。当然,您可以自由更改声明以满足您的需求:

IF OBJECT_ID('tempdb..#KValues') IS NOT NULL
BEGIN;
    DROP TABLE #KValues;
END;

CREATE TABLE #KValues
(
    [value] CHAR(1)
);

INSERT INTO #KValues ([value])
VALUES ('A')
      ,('B')
      ,('C')
      --,('D');

DECLARE @DynamicTSQLStatement NVARCHAR(MAX);

WITH DataSource AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY [Value]) AS [ValueID]
          ,[Value]
    FROM #KValues
),
DataSourceColumns AS
(
    SELECT STUFF
    (
        (
            SELECT ',K' + CAST([ValueID] AS VARCHAR(12)) + '.[Value]' 
            FROM DataSource
            ORDER BY [ValueID]
            FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)')
        ,1
        ,1
        ,''
    ) AS [Columns]
)
SELECT @DynamicTSQLStatement = 'SELECT ' + (SELECT [Columns] FROM DataSourceColumns) +
' FROM #KValues AS K1' +
STUFF
(
    (
        SELECT ' CROSS JOIN #KValues AS K' + CAST([ValueID] AS VARCHAR(12)) 
        FROM DataSource
        ORDER BY [ValueID]
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
    ,1
    ,26
    ,''
) + ' ORDER BY ' + (SELECT [Columns] FROM DataSourceColumns);

EXECUTE sp_executesql @DynamicTSQLStatement;