【问题标题】:Postgres CROSSTAB Query not able to get all the expected ColumnsPostgres CROSSTAB 查询无法获得所有预期的列
【发布时间】:2021-03-07 05:12:47
【问题描述】:

我在 PostgreSQL 中有一张像这样的表 (Img1)

从这个表中我试图实现这个(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)中显示的预期输出?

【问题讨论】:

  • 请始终以 文本 的形式提供数据,而不是图像。还包括表定义和您的 Postgres 版本。

标签: sql postgresql pivot crosstab unpivot


【解决方案1】:

你可以只使用条件聚合:

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;

【讨论】:

    【解决方案2】:

    要返回 “额外”列,您需要 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小提琴here

    详细解释:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 2016-11-26
      • 1970-01-01
      相关资源
      最近更新 更多