Access / SQL - 根据列ID将多列拆分为多行

时间:2014-03-19 15:40:03

标签: sql sql-server

我尝试过一些事情,但却无法有效地运作。救命啊!

客户数据集示例(基本上是超过100个传感器板读数的转储,每块板有42个传感器)

| BoardName | ReadingTime | Sensor1 | Sensor2 | Sensor3 | Sensor4 ... Sensor42      |
-------------------------------------------------------------------------------------
| BoardA    | 1224201301  |      18 |      24 |      7  | etc etc for each column   |
| BoardB    | 1224201301  |      18 |      23 |      8  | etc etc for each column   |
| BoardC    | 1224201301  |      17 |      24 |      7  | etc etc for each column   |
| BoardD    | 1224201301  |      16 |      23 |      6  | etc etc for each column   |
| BoardA    | 1224201302  |      18 |      22 |      5  | etc etc for each column   |
| BoardB    | 1224201302  |      18 |      23 |      5  | etc etc for each column   |
-------------------------------------------------------------------------------------

这似乎是一种非常低效的表格设计。我希望将它更像SQL,就像下面的示例一样,这使得数据更易于访问。

| SensorID | ReadingTime | SensorValue |
----------------------------------------
| BrdASen1 | 1224201301  |          18 |
| BrdASen2 | 1224201301  |          24 |
| BrdASen3 | 1224201301  |           7 |
| BrdBSen1 | 1224201301  |          18 |
| BrdBSen1 | 1224201301  |          23 |
| BrdBSen1 | 1224201301  |           8 |
| etc etc                              |
----------------------------------------

基本上,我想迭代导入数据的每一行,将42列拆分成具有3列SensorID / Date / Value格式的单独行。

1 个答案:

答案 0 :(得分:0)

我会使用这个表结构:

|BoardName|SensorId| ReadingTime | SensorValue | 
------------------------------------------------
|BoardA   |    1   | 1224201301  |          18 |
|BoardA   |    2   | 1224201301  |          24 |

SensorId值为1 - 42。 要填充表格,您需要使用UNPIVOT operator