我有一个动态选择查询,它应该将列提取为col1
,col2
...... col9
,col10
,但它会以{{{ 1}},col1
,col10
,col11
,col12
....由于查询是动态的,因此不确定如何选择它们。
请帮忙。
这是我一直在使用的动态选择。
col2
答案 0 :(得分:0)
如果您使用COALESCE或STUFF来构建列,请确保存在ORDER
此外,您可以使用col01,col02,.. col10来确保序列
答案 1 :(得分:0)
Drop Table #Prgmg
CREATE TABLE #Prgmg (
prgmg_product_id INT
,source_id_other INT
);
INSERT #Prgmg (
prgmg_product_id
,source_id_other
)
VALUES (3310,11478)
,(3337,10833)
,(3354,11466)
,(4039,4846)
,(4039,65454)
,(4039,65456)
,(13337,110833) -- Added to force over 10
,(13354,111466) -- Added to force over 10
,(14039,14846) -- Added to force over 10
,(14039,165454); -- Added to force over 10
DECLARE @DYColumns NVARCHAR(1000)
,@DYSqlQuery NVARCHAR(4000);
-- CREATE THE COLUMNS REQUIRED
SET @DYColumns = STUFF((
SELECT DISTINCT ','
+ N'sourceID'
+ right('00'+CAST(ROW_NUMBER() OVER (ORDER BY prgmg_product_id, source_id_other) AS NVARCHAR(10)),2)
FROM #Prgmg
FOR XML PATH('')
), 1, 1, '');
-- CREATE THE DYNAMIC SQL AND ADD IN THE CREATED COLUMNS
SET @DYSqlQuery = '
SELECT prgmg_product_id,'
+ @DYColumns
+ ' FROM (
SELECT prgmg_product_id
,CAST(N''sourceID'' + CAST(ROW_NUMBER() OVER (
PARTITION BY prgmg_product_id ORDER BY prgmg_product_id, source_id_other
) AS NVARCHAR(10)) AS NVARCHAR(100)) AS Col
,source_id_other
FROM #Prgmg S1
) X
PIVOT(MIN(source_id_other) FOR Col IN (' + @DYColumns + ')) P'
Print @DYSqlQuery
--EXECUTE sp_executesql @DYSqlQuery;
返回 - 请注意列是按顺序排列的。这是通过对Row_Number()
进行零填充来完成的SELECT prgmg_product_id,sourceID01,sourceID02,sourceID03,sourceID04,sourceID05,sourceID06,sourceID07,sourceID08,sourceID09,sourceID10 FROM (
SELECT prgmg_product_id
,CAST(N'sourceID' + CAST(ROW_NUMBER() OVER (
PARTITION BY prgmg_product_id ORDER BY prgmg_product_id, source_id_other
) AS NVARCHAR(10)) AS NVARCHAR(100)) AS Col
,source_id_other
FROM #Prgmg S1
) X
PIVOT(MIN(source_id_other) FOR Col IN (sourceID01,sourceID02,sourceID03,sourceID04,sourceID05,sourceID06,sourceID07,sourceID08,sourceID09,sourceID10)) P