如何在Postgresql交叉表中获取动态列数

时间:2018-03-14 06:44:36

标签: postgresql pivot-table postgresql-9.1 crosstab table-functions

我是postgresql交叉表功能的新手,并在SO上尝试了一些解决方案,但仍然卡住了。所以基本上我有一个查询导致输出如下所示:

|student_name|subject_name|marks|
|------------|------------|-----|
|John Doe    |ENGLISH     |65   |
|John Doe    |MATHEMATICS |72   |
|Mary Jane   |ENGLISH     |74   |
|Mary Jane   |MATHEMATICS |70   |
|------------|------------|-----|

我用交叉表瞄准的输出是:

|student_name| ENGLISH | MATHEMATICS |
|------------|---------|-------------|
|John Doe    | 65      | 72          |
|Mary Jane   | 74      | 70          |
|------------|---------|-------------|

我的返回第一个表(没有交叉表)的查询是:

SELECT student_name, subject_name, sum(marks) as marks FROM (
    SELECT student_id, student_name, class_name, exam_type, subject_name, total_mark as marks, total_grade_weight as out_of, percentage, grade, sort_order
    FROM(
        SELECT  student_id, student_name, class_name, exam_type, subject_name, total_mark, total_grade_weight, ceil(total_mark::float/total_grade_weight::float*100) as percentage,
            (select grade from app.grading where (total_mark::float/total_grade_weight::float)*100 between min_mark and max_mark) as grade, sort_order
        FROM (
            SELECT --big query with lots of JOINS
        ) q ORDER BY sort_order
    )v GROUP BY v.student_id, v.student_name, v.class_name, v.exam_type, v.subject_name, v.total_mark, v.total_grade_weight, v.percentage, v.grade, v.sort_order
    ORDER BY student_name ASC, sort_order ASC
    )a
    GROUP BY student_name, subject_name
ORDER BY student_name

对于交叉表,这是我遇到列的地方。

SELECT * FROM 
crosstab(' //the query above here ',
          $$VALUES ('MATHEMATICS'::text), ('marks')$$
        ) AS ct 
(student_name text, subject_name character varying, marks numeric);

如果我如上所示运行它,这就是我最终的结果:

|student_name|subject_name|marks|
|------------|------------|-----|
|John Doe    | 65         |     |
|Mary Jane   | 74         |     |
|____________|____________|_____|

正如其中subject_name而非ENGLISHMATHEMATICS。显然现在我看到我不需要marks列但是如何让它将所有主题名称作为列名称?他们可能是两个,他们可能是12个。

1 个答案:

答案 0 :(得分:0)

解决了它,但我更喜欢更动态的解决方案。我替换了这个;

$$VALUES ('MATHEMATICS'::text), ('marks')$$这个;

'SELECT subject_name FROM app.subjects WHERE ... ORDER BY ...'我的解决方案的缺点是最后一部分改为

(student_name text, english bigint, mathematics bigint, physics bigint, biology bigint, chemistry bigint, history bigint, ...);

也就是说,我必须按照上面选择中列出的顺序手动和完全列出所有主题。我发现这不太方便,但它确实有用。