I have a table that looks like this:
| Project | Date | System | Result |
|---|---|---|---|
| Proj1 | 07-01 | A | PASS |
| Proj1 | 07-01 | B | PASS |
| Proj1 | 07-01 | C | PASS |
| Proj1 | 07-01 | D | PASS |
| Proj1 | 07-02 | A | FAIL |
| Proj1 | 07-02 | B | FAIL |
| Proj1 | 07-02 | C | FAIL |
| Proj1 | 07-02 | D | FAIL |
| Proj2 | 07-01 | E | PASS |
| Proj2 | 07-01 | F | FAIL |
| Proj2 | 07-02 | E | PASS |
| Proj2 | 07-02 | F | PASS |
I want it to end up like this:
| Project | Date | A | B | C | D | E | F |
|---|---|---|---|---|---|---|---|
| Proj1 | 07-01 | PASS | PASS | PASS | PASS | ||
| Proj1 | 07-02 | FAIL | FAIL | FAIL | FAIL | ||
| Proj2 | 07-01 | PASS | PASS | FAIL | |||
| Proj2 | 07-02 | PASS | PASS | PASS |
I was also wondering if it was possible to produce something like this where the order of the various systems are just alphabetical.
| Project | Date | System1 | System2 | System3 | System4 |
|---|---|---|---|---|---|
| Proj1 | 07-01 | A-PASS | B-PASS | C-PASS | D-PASS |
| Proj1 | 07-02 | A-FAIL | B-FAIL | C-FAIL | D-FAIL |
| Proj2 | 07-01 | E-PASS | F-FAIL | ||
| Proj2 | 07-02 | E-PASS | F-PASS |
I have been trying for the last few days with the crosstab function and I am not able to reproduce the results I want. Any help would be much appreciated - thank you so much!
Try the following without using
Crosstab:See a demo from db-fiddle.
If the
Systemcolumn has an undetermined number of values (as you commented), then you have to useDynamic SQL. I'm not proffenceinal in that, but the following will pay the bill:First, create a function to prepare the dynamic statement as the following:
Now, call that function to create the prepared statement and execute that statement as the following:
Where
pvtstmtis the name of the prepared statement in the function.See a demo from db-fiddle.
Note: in the demo, the label
$body$is replaced with a single quote, just to run the function on the fiddle.For the second version of the output format, (System1, System2,...) instead of system name, you may use a view that return
Row_Number() Over (Partition By Project,Date_ Order By System_). So thepvt()function will be as the following:Check this demo.