I know, this question is not new and I read a lot of examples here, but couldn't find the solution for my task:
I have mainly two tables, related by 1:n. The TestPlan_Measure_Modules_Sensors which is a collection of sensor channels and the channels themselves in the table Machine_TestResults_Values.
The number of channels varies for each TestPlan_Measure_Modules_Sensors.
Here are the definitions:
The id_TestPlan_Measure_Module_Sensors is linked to the sensor definition.
Assuming, that the "Drehzahl" sensor has two values, a query results in following table:
SELECT
TestPlan_Measure_Module_Sensors.SensorName, LineNumber, Value
FROM
Machine_TestResults_Sensors
LEFT JOIN
Machine_TestResults_Values ON Machine_TestResults_Sensors.id = Machine_TestResults_Values.id_Machine_TestResults_Sensors
LEFT JOIN
TestPlan_Measure_Module_Sensors ON Machine_TestResults_Sensors.id_TestPlan_Measure_Module_Sensors = TestPlan_Measure_Module_Sensors.id
WHERE
id_Machine_Measure_Modules = 253
Now I need to switch rows and columns to get an output like this:
I assume I need dynamic SQL to achieve results based on the variable number of columns and a proper Pivot statement. But Pivot in SQL Server is not really my strength, so I hope someone here can hep me.
UPDATE: Thx to the hint, I tried the solution SQL Server dynamic PIVOT query?
My example, adjusted to solution in above link, results in following table:
Any idea how to get rid of the first 'NULL' line ?
UPDATE: I added a DELETE statement into the query, now it looks like it should.
Here is my version of the query:
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
SELECT
TestPlan_Measure_Module_Sensors.SensorName, LineNumber, Value
FROM
Machine_TestResults_Sensors
LEFT JOIN
Machine_TestResults_Values ON Machine_TestResults_Sensors.id = Machine_TestResults_Values.id_Machine_TestResults_Sensors
LEFT JOIN
TestPlan_Measure_Module_Sensors ON Machine_TestResults_Sensors.id_TestPlan_Measure_Module_Sensors = TestPlan_Measure_Module_Sensors.id
WHERE
id_Machine_Measure_Modules = 253
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.SensorName)
FROM #temp c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @query = 'SELECT LineNumber, ' + @cols + ' INTO #pt from
(
select LineNumber,
[Value],
SensorName
from #temp
) x
pivot
(
max([Value])
for SensorName in (' + @cols + ')
) p; DELETE FROM #pt WHERE LineNumber IS NULL; SELECT * FROM #pt;'
Execute(@query);
DROP TABLE #temp