在mysql中将行数据转换为列数据

zqdjd7g9  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(368)

我有一个数据的科目明智的学生分数在一行。我想把它转换成每个学生的列。
我已经经历了堆栈溢出,看到了一些解决方案,并尝试了这些,但没有任何帮助,或者我没有正确执行这些。
输入:

UID     SUBJECT     MARKS
16001   Chemistry   45
16001   CS          52
16001   English     28    
16002   Chemistry   25
16002   CS          25
16002   English     50
16011   Biology     25
16011   Chemistry   30
16011   English     40
16011   Physics     50

Expected Output
 UID       Maths    Physics  Chemistry Biology   CS   English
 16001      -        -       45         -        52     28
 16002      -        -       25         -        25     50
 16011      -        50      30         25       -      40

Query Written
select uid, 
  (case when subject='Maths' then Marks else '-' end) Maths,
  (case when subject='Physics' then Marks else '-' end) Physics,
  (case when subject='Chemistry' then Marks else '-' end) Chemistry,
  (case when subject='Biology' then Marks else '-' end) Biology,
  (case when subject='CS' then Marks else '-' end) CS,
  (case when subject='English' then Marks else '-' end) English
  from subWiseMarks
group by uid;

Output I'm getting
 UID       Maths    Physics  Chemistry Biology   CS   English
 16001      -        -       45         -        -      -
 16002      -        -       25         -        -      -
 16003      -        -       42         -        -      -
 16011      -        -       -          25       -      -

也就是说我只能得到每个学生的第一份入学申请。这个代码有什么错误。感谢您的帮助。谢谢你。

yvfmudvl

yvfmudvl1#

你可以在下面尝试-你必须在这里使用max/min聚合

select uid, 
  max(case when subject='Maths' then Marks else '-' end) Maths,
  max(case when subject='Physics' then Marks else '-' end) Physics,
  max(case when subject='Chemistry' then Marks else '-' end) Chemistry,
  max(case when subject='Biology' then Marks else '-' end) Biology,
  max(case when subject='CS' then Marks else '-' end) CS,
  max(case when subject='English' then Marks else '-' end) English
  from subWiseMarks
group by uid;
ru9i0ody

ru9i0ody2#

多个表连接到同一个表时,保持简单。mysql应该对此进行优化。
写在飞行,没有测试,但这应该工作。

SELECT
  id.UID     UID,
  math.marks Maths,
  phys.marks Pysics,
  bio.marks  Biology,
  cs.marks   CS,
  engl.marks English

FROM  (SELECT DISTINCT UID FROM subWiseMarks) id
LEFT JOIN subWiseMarks math
LEFT JOIN subWiseMarks phys  USING(UID)
LEFT JOIN subWiseMarks chem  USING(UID)
LEFT JOIN subWiseMarks bio   USING(UID)
LEFT JOIN subWiseMarks cs    USING(UID)
LEFT JOIN subWiseMarks engl  USING(UID)
WHERE math.SUBJECT = 'Maths'
AND   phys.SUBJECT = 'Physics'
AND   phys.SUBJECT = 'Chemistry'
AND   phys.SUBJECT = 'Biology'
AND   phys.SUBJECT = 'CS'
AND   phys.SUBJECT = 'English'
;

相关问题