Here you will select the values in a column to show as column in pivot
DECLARE @cols NVARCHAR (MAX)
SELECT @cols = COALESCE (@cols + ',[' + AvJT + ']', '[' + AvJT + ']')
FROM (SELECT DISTINCT AvJT FROM YourTable) PV
ORDER BY AvJT
Now pivot the query
DECLARE @query NVARCHAR(MAX)
SET @query = 'SELECT * FROM
(
SELECT date_1, StartHour,AvJT, data_source
FROM YourTable
) x
PIVOT
(
-- Values in each dynamic column
SUM(data_source)
FOR AvJT IN (' + @cols + ')
) p;'
EXEC SP_EXECUTESQL @query
If you want to do it to where column names are not dynamic, you can do the below query
SELECT DATE_1,STARTHOUR,
MIN(CASE WHEN AvJT='00001a' THEN data_source END) [00001a],
MIN(CASE WHEN AvJT='00002a' THEN data_source END) [00002a],
MIN(CASE WHEN AvJT='00003a' THEN data_source END) [00003a],
MIN(CASE WHEN AvJT='00004a' THEN data_source END) [00004a]
FROM YOURTABLE
GROUP BY DATE_1,STARTHOUR
EDIT :
I am updating for your updated question.
Declare a variable for filtering data_source
DECLARE @DATASOURCE VARCHAR(20) = '1'
Instead of QUOTENAME
, you can use another format to get the columns for pivot
DECLARE @cols NVARCHAR (MAX)
SELECT @cols = COALESCE (@cols + ',[' + Link_ID + ']', '[' + Link_ID + ']')
FROM (SELECT DISTINCT Link_ID FROM C1_May_Routes WHERE data_source=@DATASOURCE) PV
ORDER BY Link_ID
Now pivot
DECLARE @query NVARCHAR(MAX)
SET @query = 'SELECT * FROM
(
-- We will select the data that has to be shown for pivoting
-- with filtered data_source
SELECT date_1, StartHour,AvJT, Link_ID
FROM C1_May_Routes
WHERE data_source = '+@DATASOURCE+'
) x
PIVOT
(
-- Values in each dynamic column
SUM(AvJT)
-- Select columns from @cols
FOR Link_ID IN (' + @cols + ')
) p;'
EXEC SP_EXECUTESQL @query
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…