运行 WHERE 平均聚合结果 - postgresql

Run WHERE over an Average aggregation result - postgresql

我有以下获取论文成绩列表的查询。

SELECT DISTINCT papers.paper_id, papers.paper_title, AVG(paper_judge_participations.paper_judge_participation_score) AS final_grade,
(SELECT array_agg(paper_author_name) FROM paper_authors as authors WHERE authors.paper_id=papers.paper_id )::varchar as paper_author_name
FROM papers 
FULL JOIN paper_categories ON paper_categories.paper_category_id=papers.paper_category_id
LEFT JOIN paper_judge_participations ON papers.paper_id = paper_judge_participations.paper_id 
WHERE ((papers.paper_note IS NULL AND final_grade >= 7) OR (papers.paper_note IS NOT NULL AND papers.paper_note >= 7)) AND papers.paper_category_id = 1
GROUP BY papers.paper_id ORDER BY final_grade, papers.paper_note;

我想查看平均值结果中的 final_grade 变量是否大于 7,但我收到错误消息:

ERROR:  column "final_grade" does not exist
LINE 6: WHERE ((papers.paper_note IS NULL AND final_grade >= 7) OR (...

如何在我的 WHERE 条件下使用平均结果?

distinctSELECT 中是不必要的。您还需要将逻辑移至 HAVING 子句:

SELECT p.paper_id, p.paper_title,
       AVG(pjp.paper_judge_participation_score) AS final_grade,
       (SELECT string_agg(paper_author_name)
        FROM paper_authors pa
        WHERE pa.paper_id = p.paper_id
       ) as paper_author_name
FROM papers p LEFT JOIN
     paper_categories pc
     ON pc.paper_category_id = p.paper_category_id LEFT JOIN 
     paper_judge_participations pjp
     ON p.paper_id = pjp.paper_id 
HAVING p.paper_category_id = 1
GROUP BY p.paper_id
HAVING (p.paper_note IS NULL AND final_grade >= 7) OR
       (p.paper_note IS NOT NULL AND p.paper_note >= 7) AND 
ORDER BY final_grade, p.paper_note;

评论:

  • FULL OUTER JOINWHERE 子句变成了 LEFT OUTER JOIN。所以,你不妨明确一点。
  • 与其使用 array_agg() 并将结果转换为字符串,不如使用 string_agg() 怎么样?
  • Table 别名使查询更易于编写和阅读。
  • 当然,关于最终成绩的条件已移至 HAVING 条款。组上的条件停留在WHERE.

就我个人而言,我觉得奇怪的是,您对一个聚合使用相关子查询,而对另一个聚合使用显式聚合。我想这是一个偏好问题。在这种情况下,您可以考虑对两者都使用相关子查询。