I've tried so hard to understand how to create a pivot table in SQL, but I can't manage it!
I have the following columns:
link_id route_section date_1 StartHour AvJT data_source
....... ............. ....... ........... ...... ............
With 600,000 rows of data.
I need them in the following pivot table;
date_1
StartHour as column headingslink_id
as the row headingAvJT
as the data- with
data_source
= '1' as the filter.
PIVOT TABLE
Link_ID
date_1 StartHour 00001a 000002a 000003a 000004a
20/01/2014 8 456 4657 556 46576
21/01/2014 8 511 4725 601 52154
22/01/2014 8 468 4587 458 47585
23/01/2014 8 456 4657 556 46576
24/01/2014 8 456 4657 556 46576
25/01/2014 8 456 4657 556 46576
26/01/2014 8 456 4657 556 46576
I've managed to get the following code, this works but only gives me date_1 as column heading and not StartHour additionally, or with the filter as date_source = '1'.
Use [C1_20132014]
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT @ColumnName= ISNULL(@ColumnName + ',','')
+ QUOTENAME(Link_ID)
FROM (SELECT DISTINCT Link_ID FROM C1_May_Routes) AS Link_ID
--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
N'SELECT Date_1, ' + @ColumnName + '
FROM C1_May_Routes
PIVOT(SUM(AvJT)
FOR Link_ID IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery
Thanks for any help,
Henry
Here you will select the values in a column to show as column in pivot
Now pivot the query
If you want to do it to where column names are not dynamic, you can do the below query
EDIT :
I am updating for your updated question.
Declare a variable for filtering
data_source
Instead of
QUOTENAME
, you can use another format to get the columns for pivotNow pivot
A crosstab would be something like this. FWIW, I would recommend using better column names than 00001a. Give your column names some meaning so they are easier to work with.