我需要在动态PIVOT中转换SELECT(image here),其中可以有任何表单名称,每个表单可以有不同的输入名称和数量。
我已经根据表单中的最大输入数量设置了脚本。但我不确定如何在此之后采取行动。
DECLARE @ColumnName AS NVARCHAR(MAX);
DECLARE @i INT = 1;
DECLARE @max int =
(SELECT
MAX(y.qtd)
FROM (SELECT TOP 10
frm_Form,
frm_Name,
COUNT(inp_Input) AS qtd
FROM orb_Forms
INNER JOIN orb_FormInputs
ON frm_Form = fri_Form
INNER JOIN orb_Inputs
ON fri_Input = inp_Input
WHERE frm_Operation = 1
AND frm_Enabled = 1
AND fri_Enabled = 1
AND inp_Enabled = 1
GROUP BY frm_Form,frm_name
ORDER BY frm_Form desc) y)
WHILE (@i <= @max)
BEGIN
select @ColumnName = ISNULL(@ColumnName + ',','') + QUOTENAME('Input' + CAST(@i as nvarchar));
SET @i = @i + 1;
END
结果:[输入1],[输入2],[输入3],[输入4],[输入5],[输入6],[输入7],[输入8],[输入9], [输入10],[输入11]
答案 0 :(得分:0)
一些测试数据
CREATE TABLE orb_Forms(
frm_Form varchar(20),
frm_Name varchar(20),
)
CREATE TABLE orb_FormInputs(
fri_Form varchar(20),
fri_Input varchar(20)
)
CREATE TABLE orb_Inputs(
inp_Input varchar(20)
)
INSERT orb_Forms(frm_Form,frm_Name)VALUES
('1','form 1'), ('2','form 2')
INSERT orb_FormInputs(fri_Form,fri_Input)VALUES
('1','color'), ('1','car'),
('2','test 1'), ('2','test 2'), ('2','test 3'), ('2','test 4')
INSERT orb_Inputs(inp_Input)VALUES
('color'), ('car'), ('test 1'), ('test 2'), ('test 3'), ('test 4')
测试查询
DECLARE @ColumnName varchar(MAX)='[Input 1],[Input 2],[Input 3],[Input 4],[Input 5],[Input 6],[Input 7],[Input 8],[Input 9],[Input 10],[Input 11]'
DECLARE @query varchar(MAX)='
SELECT frm_Form,frm_Name,'+@ColumnName+'
FROM
(
SELECT TOP 10 WITH TIES
frm_Form,
frm_Name,
inp_Input,
CONCAT(''Input '',ROW_NUMBER()OVER(PARTITION BY frm_Form,frm_Name ORDER BY inp_Input)) ColumnName
--''Input ''+CAST(ROW_NUMBER()OVER(PARTITION BY frm_Form,frm_Name ORDER BY inp_Input) AS varchar(10)) ColumnName
FROM orb_Forms
INNER JOIN orb_FormInputs ON frm_Form = fri_Form
INNER JOIN orb_Inputs ON fri_Input = inp_Input
--WHERE frm_Operation = 1
-- AND frm_Enabled = 1
-- AND fri_Enabled = 1
-- AND inp_Enabled = 1
ORDER BY frm_Form desc
) q PIVOT(MAX(inp_Input) FOR ColumnName IN('+@ColumnName+')) p
'
PRINT @query -- check the query
EXEC(@query)