I've got an issue regarding two tables in my database that have the following columns:
COMMENT table
KEY
TYPE
NUMBER
TEXT
Composite key made up of (KEY, TYPE, NUMBER)
RESULTS table
KEY
TYPE1
TYPE2
...
TYPE20
TEXT1
TEXT2
...
TEXT20
An example of the COMMENT table would be this:
KEY | TYPE | NUMBER | TEXT|
1 A 0001 SAMPLETEXT
1 A 0002 SAMPLETEXT2
1 B 0001 SAMPLETEXT3
1 B 0002 SAMPLETEXT4
1 B 0003 SAMPLETEXT5
2 C 0001 SAMPLETEXT6
2 C 0002 SAMPLETEXT7
3 A 0001 SAMPLETEXT8
For each KEY, there are only 3 different types A,B,C and one TYPE may have up to 0020 in the NUMBER field. These records are ordered by KEY then by TYPE
I need to accomplish the following: for each KEY in COMMENT table, insert the first 20 TYPE rows into each column inside de RESULTS table (TYPE1 for the first type in the Comment table, TYPE2 for the second type in the comment table and so on) and insert the first 20 TEXT rows into each column inside the RESULTS table (TEXT1 for the first text, TEXT2 for the second text and so on)
The RESULTS table would look like this:
KEY | TYPE1 | TYPE2 | TYPE3 | ... | TYPE20 | TEXT1 | TEXT2 | ... | TEXT20
1 A A B NULL SAMPTE1 SAMPTE2 NULL
2 C C NULL NULL SAMPTE6 SAMPTE7 NULL
3 A NULL NULL ... NULL SAMPTE7 NULL .... NULL
The RESULTS table would have a row per each KEY and up to 20 TEXT fields along with their corresponding type.
As you can see, this RESULTS table was clearly bad designed. It was made in the 70's and we can't change it.
Some questions might pop up when implementing this, here are the answers:
- What if a KEY has more than 20 TEXT in the
COMMENTtable? We don't care, we just insert the first 20 of them - What if I have 23 type A text and 10 type B text, for example? Then just the first 20 type A text would appear in
RESULTS - Is there any way the
RESULTStable could be changed? Unfortunately there isn't. - Does TYPE1 match TEXT1 in the
RESULTStable and TYPE2 match TEXT2 and so on? Yes, also, the amount of columns that match is the same. - If there are less than 20 TEXT in
COMMENTtable, the rest of the values of TEXT and TYPE in RESULTS is null? Yes
The question is, what is the cleanest, fastest, scalable, non tedious way of implementing this?
Also, how could it be implemented, such that in a future the RESULTS table could have N more TYPE columns and N more TEXT columns?
I've heard about using PIVOT tables, joins and many other techniques but I don't know how to make this thing happen.