sql >> Database teknologi >  >> RDS >> PostgreSQL

Sådan opretter du kolonner til forskellige felter uden at anvende pivoteringsfunktionen

Hvis du har et fast antal kolonner, kan du bruge en matrix:

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

Bemærk, at distinct er normalt ikke nødvendig, når du bruger group by



  1. PostgreSQL underforespørgsel ved hjælp af like

  2. PostgreSQL-agent i SQL Standard Committee igen

  3. udtræk understreng fra mysql kolonne ved hjælp af regex

  4. Få alle poster fra MySQL-databasen, der er inden for Google Maps .getBounds?