I use a Linq-2-Sql at the moment in order to perform a fairly complicated query. It is however very inefficient and results in multiple round trips being made to the server.
Using some joins I have managed to get the data into a format like this:
Sensor -- Timestamp -- Value
A -- 12/02/2013 09:00 -- 10.4
A -- 12/02/2013 10:00 -- 10.3
A -- 12/02/2013 11:00 -- 10.1
B -- 12/02/2013 09:00 -- 15.3
B -- 12/02/2013 10:00 -- 16.4
B -- 12/02/2013 11:00 -- 15.4
I desire this in an output like
TimeStamp -- SensorA -- SensorB
12/02/2013 09:00 -- 10.4 -- 15.3
12/02/2013 10:00 -- 10.3 -- 16.4
12/02/2013 11:00 -- 10.1 -- 15.4
I am guessing I need a dynamic pivot? Can anybody help point me in the right direction?
EDIT – Obviously there are more than the 2 sensors…ideally I need this to be able to scale out in terms of columns. I don’t even know if SQL Server can do this so any help is appreciated.
You will want to use the
PIVOTfunction to transform the data.If you have a limited number of
Sensorvalues, then you can hard-code the query:See SQL Fiddle with Demo
But if the values are unknown then you will want to implement dynamic SQL:
See SQL Fiddle with Demo
Both will give the result:
Note, you will replace the
yourtablewith your current query.Edit #1, if you want to filter by date, you could use the following dynamic sql:
See SQL Fiddle with Demo