I trying to write a query and I need some help.
I have some data that looks like this:
However, the end users would like a Pivot so that the data displays like this:
I wrote this code:
SELECT *
FROM
(
SELECT TOP 100
Log0.sn
,CONVERT(VARCHAR(50), Log0.capture_time) AS Instant
,CONVERT(VARCHAR(50),Log0.address) + '/' + Log0.[Key] AS 'Address/Key'
,Log0.average AS Command
,Log1.average AS Actual
FROM ih3_fan_speed_log_0 Log0
LEFT JOIN ih3_fan_speed_log_01 Log1 ON Log0.sn = Log1.sn AND
Log0.capture_time = Log1.capture_time AND Log0.address = Log1.address
WHERE Log0.sn = 'V300188' AND Log0.capture_time = '03/26/2017 13:05:00'
) Src
pivot
(
MAX(sn)
for Instant in ([1], [2], [3], [4])
) piv;
But that returns:
My questions are:
1) Why doesn't my Pivot work ? 2) Is it even possible to do what I need with a Pivot ?
Thanks for any help.
Per request, here is the data:
sn Instant Address/Key Command Actual
V300188 Mar 26 2017 1:05PM 1/EF-1 99.23 99.24
V300188 Mar 26 2017 1:05PM 2/EF-2 99.02 99.04
V300188 Mar 26 2017 1:05PM 3/EF-3 100 0
V300188 Mar 26 2017 1:05PM 4/EF-4 100 100
V300188 Mar 26 2017 1:05PM 41/MUA-1 74.58 74.58
V300188 Mar 26 2017 1:05PM 51/0-10VDC 74.58 74.58
Here is the result set:
Address/Key Command Actual 1 2 3 4
1/EF-1 99.23 99.24 NULL NULL NULL NULL
2/EF-2 99.02 99.04 NULL NULL NULL NULL
3/EF-3 100 0 NULL NULL NULL NULL
4/EF-4 100 100 NULL NULL NULL NULL
41/MUA-1 74.58 74.58 NULL NULL NULL NULL
51/0-10VDC 74.58 74.58 NULL NULL NULL NULL
Here is how you can leverage a dynamic crosstab to accomplish this type of thing. Jeff Moden has a fantastic article explaining this technique here. http://www.sqlservercentral.com/articles/Crosstab/65048/
Another Option for a Dynamic Pivot
The twist was the non-distinct/repeating columns in the final results. As you can see, this was resolved with a simple replace (x3).
Returns
The generated SQL Looks like this