如何在不应用透视功能的情况下为不同字段创建列

时间:2018-05-29 10:16:09

标签: sql postgresql postgresql-9.3

所以我对这个坚强的人有疑问!我有一段时间遇到这个概念的问题,我需要将其清除...... 以下代码显示拥有1种以上语言的学生

SELECT DISTINCT s.studentnumber as studentnr, 
    p.firstname AS name,
    sl.gradenumber as gradenumber,
    string_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 

结果

result1

现在我的问题很简单,但我不确定答案是什么......我想把这些语言分开并将它们放在单独的字段中,所以它看起来像这样

通缉结果

wantedresult

还有一个主要问题。这是使用Postgresql 9.3 ,它现在不允许分组设置或汇总或多维数据集。我尝试了这个代码,但它无法正常工作,我不知道如何处理它,我不知道如何继续前进......

(select distinct l.text 
            from language 
            join pupillanguage pl2 on pl2.languageid = language.id 
            join pupil on p.id = pl2.personid
            limit 1) as language1

这就是表格的样子

Language Table 
iD                   PK
shorttext            char varying
text                 char varying

PupilLanguage Table

id                   PK
languageid           FK
personid             FK
displayorder         int

2 个答案:

答案 0 :(得分:1)

SQL查询返回固定数量的列。如果您只需要三个附加列,则可以使用动态聚合:

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;

但是,如果您想要一个变量号,那么您需要crosstab或动态SQL。我可能还建议您考虑使用数组。

答案 1 :(得分:1)

如果您有固定数量的列,则可以使用数组:

distinct

请注意,使用group by

时通常不需要Redirect permanent / https://mysite.example.com/