根据条件将行转移到列

时间:2016-06-22 17:11:55

标签: mysql sql pivot

我有一张像这样的桌子

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

我想像这样安排

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

枢轴的概念是

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;

我无法在我的情况下弄清楚,因为我正在创建列s1-s4,即每个学生的第一个得分变为s1,第二个成为s2等。

我该如何解决这个问题

1 个答案:

答案 0 :(得分:3)

最简单的方法是将值放在一列中:

select student_id, group_concat(score order by id)
from t
group by student_id;

这足以用于许多目的。如果需要单独的列,则需要创建列。一种方法使用变量:

select student_id,
       max(case when rn = 1 then score end) as score_1,
       max(case when rn = 2 then score end) as score_2,
       max(case when rn = 3 then score end) as score_3,
       max(case when rn = 4 then score end) as score_4
from (select t.*,
             (@rn := if(@s = student_id, @rn + 1,
                        if(@s := student_id, 1, 1)
                       )
             ) as rn
      from t cross join
           (select @s := -1, @rn := 0) params
      order by student_id, id
     ) t
group by student_id;