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

前端 未结 2 1627

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:24

    A SQL query returns a fixed number of columns. If you want just three additional columns, then you can use dynamic aggregation:

    with t as (
          SELECT s.studentnumber as studentnr, p.firstname AS name,
                 sl.gradenumber as gradenumber, l.text as language,
                 dense_rank() over (partition by s.studentnumber, p.firstname, sl.gradenumber order by l.text) as seqnum
          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
         )
    select studentnr, name, gradenumber,
           max(case when seqnum = 1 then language end) as language_1,
           max(case when seqnum = 2 then language end) as language_2,
           max(case when seqnum = 3 then language end) as language_3
    from t
    group by studentnr, name, gradenumber;
    

    However, if you want a variable number, then you need crosstab or dynamic SQL. I might also suggest that you consider arrays instead.

提交回复
热议问题