How to create columns for different fields without applying the pivoting function

前端 未结 2 1611

So i have a question for the tough hearted! I have had an issue with this concept for awhile and I need it to be cleared... The following code shows students who have more than

2条回答
  •  被撕碎了的回忆
    2021-01-27 12:36

    If you have a fixed number of columns, you can use an array:

    select studentnr, name, gradenumber, 
           languages[1] as language_1,
           languages[2] as language_2,
           languages[3] as language_3,
           languages[4] as language_4,
           languages[5] as language_5
    FROM (       
      SELECT s.studentnumber as studentnr, 
             p.firstname AS name,
             sl.gradenumber as gradenumber,
             array_agg(DISTINCT l.text) as languages
      FROM student s
          JOIN pupil p ON p.id = s.pupilid    
          JOIN pupillanguage pl on pl.pupilid = p.id
          JOIN language l on l.id = pl.languageid
          JOIN schoollevel sl ON sl.id = p.schoollevelid
      GROUP BY s.studentnumber, p.firstname
    ) t
    

    Note that distinct is usually not needed when you use group by

提交回复
热议问题