Postgres CROSSTAB 查询无法获得所有预期的列

Postgres CROSSTAB Query not able to get all the expected Columns

我在 PostgreSQL 中有一个 table 是这样的 (Img1)

从这个table我正在努力实现这个(Img2)

我正在尝试使用 CROSSTAB 来执行此操作,但在这样做时我无法获得 Roll No 列。下面是我正在使用的查询。

SELECT * 
FROM CROSSTAB
('select student, subject, marks from dummy order by 1,2') 
AS FINAL
(
    Student TEXT, 
    Geography NUMERIC,
    History NUMERIC,
    Language NUMERIC,
    Maths NUMERIC,
    Music NUMERIC
);

如何实现我在 (Img2) 中显示的预期输出?

您可以只使用条件聚合:

select student,
       max(marks) filter (where subject = 'Music') as music,
       max(marks) filter (where subject = 'Maths') as maths,
       max(marks) filter (where subject = 'History') as history,
       max(marks) filter (where subject = 'Language') as language,
       max(marks) filter (where subject = 'Geography') as geography,
       rollno
from t
group by student, rollno;

至 return “额外”列,您需要 crosstab() 的 2 参数形式功能(这通常是你想要的):

SELECT * 
FROM  crosstab(
   'SELECT student, roll_no, subject, marks
    FROM   dummy
    ORDER  BY 1'
 , $$SELECT unnest('{Geography, History, Language, Maths, Music}'::text[])$$
   ) AS final (
      "Student"   text
    , "Roll No"   text  -- extra column(s) go here
    , "Geography" int
    , "History"   int
    , "Language"  int
    , "Maths"     int
    , "Music"     int
);

db<>fiddle here

详细解释:

  • PostgreSQL Crosstab Query
  • Pivot on Multiple Columns using Tablefunc