Question

I have the following data format in sql db2:

ID   Test_no   Result
--   -------   ------
01   1         A
01   2         B
01   3         B
02   1         A
03   1         B
03   2         C
04   1         A

where person can take a maximum of 3 tests, although some only take a minimum of 1 test (the criteria is irrelevant). I have been asked to produce the table in, and I hate to use this phrase "wide format" i.e.

ID   Test1    Test2   Test3 
--   -----    -----   -----
01   A        B       B
02   A        NULL    NULL
03   B        C       NULL
04   A        NULL    NULL

where each person has one record and records the result if they took a certain test (Although I don't like working in this format!) I can do something like

select distinct ID,
       case when Test_no = 1 then Result end as Test1,
       case when Test_no = 2 then Result end as Test2,
       case when Test_no = 3 then Result end as Test3
from my_table

however of course this generates a new line each time a non-null test score exists and I end up with:

ID   Test1    Test2   Test3 
--   -----    -----   -----
01   A        NULL    NULL
01   NULL     B
01   NULL     NULL    C
.
.
.

How do I remove the rows that are generated as a result of a non-null test result appearing? i.e. like the previous table.

Thanks very much.

Was it helpful?

Solution

Try this way:

SELECT ID,
       MAX(case when Test_no = 1 then Result end) as Test1,
       MAX(case when Test_no = 2 then Result end) as Test2,
       MAX(case when Test_no = 3 then Result end) as Test3
FROM my_table
GROUP BY ID
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top