IF OBJECT_ID('TempDB..##ORDERS_STEPS', 'U') IS NOT NULL DROP TABLE ##ORDERS_STEPS
CREATE TABLE ##ORDERS_STEPS
(
STEP_ID INT,
ORDER_NUMBER INT,
STEP_NUMBER INT,
STEP_CODE nVARCHAR(10),
STEP_FACTOR INT
)
INSERT INTO ##ORDERS_STEPS
(STEP_ID, ORDER_NUMBER, STEP_NUMBER, STEP_CODE, STEP_FACTOR)
VALUES
(1, 10,0,'S001', 1),
(2, 10,1,'S002', 1),
(3, 10,2,'S003', 1),
(4, 20,0,'S001', 1),
(5, 20,1,'S002', 1),
(6, 20,2,'S003', 1)
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(STEP_CODE)
FROM (SELECT DISTINCT STEP_CODE FROM ##ORDERS_STEPS) AS STEP_CODE
DECLARE @ColumnValue AS NVARCHAR(MAX)
SELECT @ColumnValue= ISNULL(@ColumnValue + ', CASE WHEN ' + QUOTENAME(STEP_CODE) + ' > 0 THEN ORDER_NUMBER END AS ' + QUOTENAME(STEP_CODE),'CASE WHEN ' + QUOTENAME(STEP_CODE) + ' > 0 THEN ORDER_NUMBER END AS ' + QUOTENAME(STEP_CODE)) + CHAR(13)
FROM (SELECT DISTINCT STEP_CODE FROM ##ORDERS_STEPS) AS STEP_CODE
--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
N'SELECT ' + @ColumnValue + '
FROM (SELECT STEP_ID, ORDER_NUMBER, STEP_CODE FROM ##ORDERS_STEPS) mq
PIVOT(COUNT(STEP_ID)
FOR STEP_CODE IN (' + @ColumnName + ')) AS pt'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery