Search code examples
mysqltranspose

Tranpose the table rows to column


I have a table which looks like this:

id  response_id     name        value
6   13          gender         female
5   13          workingArea    Sch
3   12          workingArea    IT
4   12          gender         male

and I wish to convert into something like this:

response_id          workingArea   gender
12                IT           male
13                Sch          female

May I know how to do this?


Solution

  • Assuming your first table is SOURCETABLE and your second table is TARGETTABLE

    INSERT INTO TARGETTABLE(response_id, workingArea, gender)
    SELECT a.response_id response_id, 
           a.value workingArea, 
           b.value gender
      FROM SOURCETABLE a, SOURCETABLE b
     WHERE a.response_id = b.response_id
       AND a.name <> b.name
       AND a.name = 'workingArea'
       AND b.name = 'gender'