I have a query that returns me data where the channel name exists in another table so I only get back a specific set of channels.
SELECT DISTINCT
ReadingDate, SerialNumber, ChannelName, ChannelValue
FROM
[Staging].[UriData]
WHERE
ChannelName IN (SELECT ChannelName FROM [dbo].[Channels])
ORDER BY
ReadingDate DESC, ChannelName
The importance of this query is it only brings back channels that are storing moving data and not fixed diagnostic data.
Results In (snippet):
ReadingDate | SerialNumber | ChannelName | ChannelValue
2018-09-09 20:30:00 2209 m1 461
2018-09-09 20:30:00 2209 m2 0
2018-09-09 20:30:00 2209 m3 50
2018-09-09 20:30:00 2209 m4 15631
2018-09-09 20:30:00 2209 m5 1
2018-09-09 20:30:00 2209 m6 8150
2018-09-09 20:30:00 2209 m7 0
2018-09-09 20:30:00 2209 m8 2790
2018-09-09 20:30:00 2209 m9 0
2018-09-09 20:15:00 2209 m1 2452
2018-09-09 20:15:00 2209 m2 0
2018-09-09 20:15:00 2209 m3 50
2018-09-09 20:15:00 2209 m4 15629
2018-09-09 20:15:00 2209 m5 1
2018-09-09 20:15:00 2209 m6 8100
2018-09-09 20:15:00 2209 m7 0
2018-09-09 20:15:00 2209 m8 2780
I then want to pivot this data into columns so they are grouped by the day (date), then the time is taken from that date.
Required output:
DATE | SERIAL | ChannelName | 00:15 | 00:30 | ..... | 23:45
2018-09-06 2209 m1 Value Value ..... Value
2018-09-06 2209 m2 Value Value ..... Value
I have been playing around with pivots but I am not getting the data in the format I need as described.
You can try to use cte recursion make a time calendar table, then make row number by the
time
.then use dynamic SQL with pivot to make it.
Here is a sample for you.
sqlfiddle
You can also achieve the same result using
PIVOT
construct as follows:To generate "Time" columns (and save you from having to type manually) run the below query:
Copy/paste the result into the "PIVOT" query above.