簡體   English   中英

根據條件將行旋轉到列

[英]pivot rows to columns based on condition

我有這樣的桌子

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等。

我該如何解決

最簡單的方法是將值放在單個列中:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM