Merging mutliple rows from one table into columns in an other
Hello,
I have two tables. One is an export from a different database and one is the
destination table.
The Export table looks something like this:
EmpID = the ID of an employee
Contract = Code for the contract(s) the employee might have
MainContract = if -1 it's the main contract, else sub-contracts
| EmpID | Contract | MainContract |
------------------------------------------
| 1 | A | -1 |
| 1 | B | 0 |
| 1 | C | 0 |
| 2 | C | 0 |
| 1 | D | -1 |
The destination table is something like this
| EmpID | Contract1 | Contract2 | Contract3
---------------------------------------------------
| 1 | A | |
| 2 | D | |
To get the main contracts in the Contract1 column is no problem, since there
will always be only one row in the export table with the MainContract set to
-1 for each EmpID.
Now my question is how I can loop through the sub-contracts and one by one
fill them out in the Destination table in the subsequent columns so the
result would be something like this:
| EmpID | Contract1 | Contract2 | Contract3
---------------------------------------------------
| 1 | A | B | C
| 2 | D | C |
Normally I would use some code in my application, but this has to be done in
a Stored Procedure.
Thanks in advance!!!!
|