1

I have 2 tables, student table that contains regNo and name columns; and reg_subject table which contains list of subjects registered individually by students. A student can register more than one subject.

I want to generate a table that will join the two tables such that the reg_subject table will be transposed in a way that the rows will turn to be the columns. The two tables as well as the resultant table are sketched below.

student table

| regNo | name  |
_________________
| 1001  | Saleh |
-----------------
| 1002  | Moses |
-----------------
| 1003  | Hafsa |

reg_subject table

| regNo | subject  |
____________________
| 1001  | English  |
--------------------
| 1001  | Math     |
--------------------
| 1002  | English  |
--------------------
| 1003  | Math     |
--------------------
| 1002  | Math     |
--------------------
| 1003  | Physics  |
--------------------
| 1001  | Physics  |
--------------------
| 1002  | Physics  |
--------------------

the transposed join table should look like this:

The transposed joint table

| regNo | name  | subject1 | subject2 | subject3 |
__________________________________________________
| 1001  | Saleh | English  | Math     | Physics  |
--------------------------------------------------
| 1002  | Moses | English  | Math     | Physics  |
--------------------------------------------------
| 1003  | Hafsa |          | Math     | Physics  |
--------------------------------------------------

1 Answers1

0
 SELECT regNo, name,               
        MAX( CASE WHEN subject = 'English'
                  THEN subject
             END) as subject1,
        MAX( CASE WHEN subject = 'Math'
                  THEN subject
             END) as subject2,
        MAX( CASE WHEN subject = 'Physics'
                  THEN subject
             END) as subject3
FROM YourTable
GROUP BY regNo, name
Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118