Is there a T-SQL (SQL Server 2008R2) query to transform TABLE_1 into the expected resultset?
TABLE_1
+----------+-------------------------+---------+------+
| IdDevice | Timestamp | M300 | M400 |
+----------+-------------------------+---------+------+
| 3 | 2012-12-05 16:29:51.000 | 2357,69 | 520 |
| 6 | 2012-12-05 16:29:51.000 | 1694,81 | 470 |
| 1 | 2012-12-05 16:29:51.000 | 2046,33 | 111 |
+----------+-------------------------+---------+------+
Expected resultset
+-------------------------+---------+--------+---------+--------+---------+--------+
| Timestamp | 3_M300 | 3_M400 | 6_M300 | 6_M400 | 6_M300 | 6_M400 |
+-------------------------+---------+--------+---------+--------+---------+--------+
| 2012-12-05 16:29:51.000 | 2357,69 | 520 | 1694,81 | 470 | 2046,33 | 111 |
+-------------------------+---------+--------+---------+--------+---------+--------+
This is still a
PIVOTquery but before youPIVOTyou must perform anUNPIVOTof your columns.First, you perform the
UNPIVOTwhich takes your current multiple columns and transforms them into two columns – one with the value and the other with the column name. The key for theUNPIVOTis that the datatypes be the same, so in the subquery Icastany columns to the same datatype:See SQL Fiddle with Demo
Result:
Once you complete the unpivot, then you can apply the
PIVOTfunction:See SQL Fiddle with Demo
Results:
If you have an unknown number of
IdDevicesthat you want to transform into columns, then you can use dynamic SQL:See SQL Fiddle with Demo
Edit, if you need a totals field for each m value, then you can use:
See SQL Fiddle with Demo