id Subject mark Year
-------------------------
1 Maths 32 2008
1 Science 40 2009
1 Science 45 2008
1 English 50 2009
1 English 60 2008
I am looking for a result like this:
id Maths Science English
-----------------------------
1 32 40 & 45 50 & 60
Please advise. I am using MySQL.
As @Mark suggested,
GROUP_CONCAT()can give you the following result:From this test case:
However another way to tackle the problem would be by using as sub query for each subject:
Which will give the following result:
UPDATE:
Further to the comments, it looks like you need to take the
yearfield in consideration. Luckily theGROUP_CONCAT()function takes anORDER BYclause which we can use. Let’s start from a new test case with the year field:Then we would be able to use the
GROUP_CONCAT()function with theORDER BYclause as follows:Finally, to
GROUP BYeverything in one horizontal row, we can use the subquery technique that we used in the earlier example:Which will return the following:
If you wanted the marks and the years ordered in descending order, you could simply add the
DESCkeyword after eachORDER BY year.