I have a table with several columns:
CREATE TABLE [dbo].[MyTable](
[ValueID] [int] NOT NULL,
[Timestamp] [datetime] NOT NULL,
[RealValue] [float] NOT NULL
) ON PRIMARY
+---------+----------------------+----------+
| ValueID | Timestamp |RealValue |
+---------+----------------------+----------+
| 123 | 3/1/2018 12:00:49 AM | 54.1 |
| 123 | 3/1/2018 12:01:49 AM | 55.1 |
| 123 | 3/1/2018 12:02:49 AM | 56.1 |
| 123 | 3/1/2018 12:03:49 AM | 57.1 |
| 123 | 3/1/2018 12:04:49 AM | 58.1 |
| 876 | 3/1/2018 12:00:49 AM | 1.0 |
| 876 | 3/1/2018 12:01:49 AM | 1.1 |
| 876 | 3/1/2018 12:02:49 AM | 1.2 |
| 876 | 3/1/2018 12:03:49 AM | 1.3 |
| 876 | 3/1/2018 12:04:49 AM | 1.4 |
| 63 | 3/1/2018 12:00:49 AM | 300.0 |
| 63 | 3/1/2018 12:01:49 AM | 300.5 |
| 63 | 3/1/2018 12:02:49 AM | 301.0 |
| 63 | 3/1/2018 12:03:49 AM | 301.5 |
| 63 | 3/1/2018 12:04:49 AM | 302.0 |
+---------+----------------------+----------+
I need to split this table into a "column-per-value" structure:
+----------------------+----------+----------+----------+
| Timestamp | 123 | 876 | 63 |
+----------------------+----------+----------+----------+
| 3/1/2018 12:00:49 AM | 54.1 | 1.0 | 300.0 |
| 3/1/2018 12:01:49 AM | 55.1 | 1.1 | 300.5 |
| 3/1/2018 12:02:49 AM | 56.1 | 1.2 | 301.0 |
| 3/1/2018 12:03:49 AM | 57.1 | 1.3 | 301.5 |
| 3/1/2018 12:04:49 AM | 58.1 | 1.4 | 302.0 |
+----------------------+----------+----------+----------+
Would this be possible with SQL, or is it more suited to a script?
Such as:
SELECT DISTINCT [ValueID] FROM [db].[dbo].[MyTable]
// ...Build a hash of distinct values in the script...
CREATE TABLE [dbo].[NewTable](
[123] int NOT NULL,
[876] int NOT NULL,
[63] int NOT NULL
...
) ON PRIMARY
// ...Loop through hash and populate each column with a separate query...
The table is fairly large (26 million rows) and there are ~500 distinct [ValueID]
values which would become columns in the destination table.