简体   繁体   中英

Access/SQL - split multiple columns to multiple rows based on column ID

I've tried a few things but can't get this to work efficiently. Help!

Customer dataset example (basically a dump of over 100 sensor board readings with 42 sensors per board)

| 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   |
-------------------------------------------------------------------------------------

This seems like a pretty inefficient table design. I'd like to get it into SQL more like the following example, which makes the data a little more accessible.

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

So basically, I want to iterate through each row of imported data, split off the 42 columns into individual rows with a 3-column SensorID/Date/Value format.

I would use this table structure:

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

SensorId values would be from 1 - 42. To populate the table, you'll need to use the UNPIVOT operator .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM