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
顯示您的查詢!你如何編寫查詢? –
代碼片段比您的參數化問題更易於調試。 –