Her skal du vælge de værdier i en kolonne, der skal vises som kolonne i pivot
DECLARE @cols NVARCHAR (MAX)
SELECT @cols = COALESCE (@cols + ',[' + AvJT + ']', '[' + AvJT + ']')
FROM (SELECT DISTINCT AvJT FROM YourTable) PV
ORDER BY AvJT
Drej nu forespørgslen
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
- Klik her for at se resultatet
Hvis du vil gøre det der, hvor kolonnenavne ikke er dynamiske, kan du udføre nedenstående forespørgsel
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
- Klik her for at se resultatet
REDIGERING:
Jeg opdaterer for dit opdaterede spørgsmål.
Erklære en variabel til filtrering af data_source
DECLARE @DATASOURCE VARCHAR(20) = '1'
I stedet for QUOTENAME
, kan du bruge et andet format til at få kolonnerne til pivot
DECLARE @cols NVARCHAR (MAX)
SELECT @cols = COALESCE (@cols + ',[' + Link_ID + ']', '[' + Link_ID + ']')
FROM (SELECT DISTINCT Link_ID FROM C1_May_Routes WHERE [email protected]) PV
ORDER BY Link_ID
Drej nu
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 = '[email protected]+'
) x
PIVOT
(
-- Values in each dynamic column
SUM(AvJT)
-- Select columns from @cols
FOR Link_ID IN (' + @cols + ')
) p;'
EXEC SP_EXECUTESQL @query
- Klik her for at se resultatet