dimanche 3 juillet 2016

pivot rows to columns based on condition


I have a table like so

id  student_id  score
1   1           45
2   2           55
3   2           75
4   3           80
5   1           90
6   2           78
7   3           55
8   1           45
9   1           65

I want to arrange it like this

student_id s1   s2   s3   s4
1          45   90   45   65
2          55   75   78   -
3          80   55   -    -

the concept of pivot is

SELECT
  item_id,
  MAX(IF(property_name = 'property_value1', value, NULL)) AS alias1,
  MAX(IF(property_name = 'property_value2', value, NULL)) AS alias2,
  ...
  ...
  ...
FROM
  table
GROUP BY
  item_id;

which i cannot really figure out in my case, as i am creating the columns s1 - s4 by occurrence, i.e the first score for each student becomes s1, second becomes s2 etc.

how do i solve this


Aucun commentaire:

Enregistrer un commentaire