我是 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
不是ENGLISH
或MATHEMATICS
。显然,现在我看到我不需要该marks
列,但我怎样才能让它将所有主题名称作为列名?他们可能是两个,他们可能是十二个。