To retrieve values ​​from multiple rows in a single row from a single table under multiple columns

advertisements

Here is an example table for my problem:

Database : MySql 5.1
Table Name : Education

id   edutype    university  subjects                    yearofpass    percentmarks200  1          CBSE        Maths,Science,English,Hindi     2002          78.00 200  2          CBSE        Maths,Physics,Chem,Biology      2004          68.00 200  3          WBUT        Computer Science Engineering    2008          87.00 100  1          ICSE        Maths,Science,English,Hindi     2001          72.00 100  2          CBSE        Maths,Physics,Chem,Biology      2003          65.00 100  3          NIT         Electronics Engineering         2008          75.00 300  1          CBSE        Maths,Science,English,Hindi     2003          65.00 300  2          CBSE        Maths,Physics,Chem,Biology      2005          63.00 300  3          VIT         Metallurgy Engineering          2009          79.00 

Now i would like to run a sql query which will output results in following format:

id   uvr1  sub1                           yop1  pcm1   uvr2  sub2                            yop2  pcm2   uvr3   sub3                            yop3     pcm3200  CBSE  Maths,Science,English,Hindi    2002  78.00  CBSE  Maths,Physics,Chem,Biology      2004  68.00  WBUT   Computer Science Engineering    2008     87.00 100  ICSE  Maths,Science,English,Hindi    2001  72.00  CBSE  Maths,Physics,Chem,Biology      2003  65.00  NIT    Electronics Engineering         2008     75.00 300  CBSE  Maths,Science,English,Hindi    2003  65.00  CBSE  Maths,Physics,Chem,Biology      2005  63.00  VIT    Metallurgy Engineering          2009     79.00

Please share if you have any good method to achieve this, need your help.

Thanks in Advance


You can try this:

SELECT
    e1.id,
    e1.university as uvr1,
    e1.subjects as sub1,
    e1.yearofpass as yop1,
    e1.percentmarks as pcm1,
    e2.university as uvr2,
    e2.subjects as sub2,
    e2.yearofpass as yop2,
    e2.percentmarks as pcm2,
    e3.university as uvr3,
    e3.subjects as sub3,
    e3.yearofpass as yop3,
    e3.percentmarks as pcm3
FROM
    Education as e1
LEFT JOIN Education as e2
    ON e1.id = e2.id
    AND e2.edutype = e1.edutype+1
LEFT JOIN Education as e3
    ON e1.id = e3.id
    AND e3.edutype = e1.edutype+2
WHERE
    e1.edutype = 1

But... this works only is you have no more the 3 universities with the same id if you have more you need to add extra joins.

Also looking at you table structure i think you should read more about Database Normalization it can help you .

You can do something like this: