为什么我在分组时遇到语法错误?

时间:2016-12-28 19:12:19

标签: sql postgresql

我创建了以下查询,但是当我运行它时,我在GROUP BY子句中遇到语法错误但是当我删除它时PostgreSQL给了我错误,我需要将t.bsn添加到GROUP BY子句。我该如何解决这个错误?

SELECT t.bsn
FROM teachers t, designes d, students s, course c, teaches lg
WHERE c.course_follower = s.class AND t.bsn = lg.bsn AND d.course_code = c.course_code AND d.bsn = t.bsn AND s.class = lg.class 
HAVING t.salary = (2000 + (t.scale * 200) + ((t.scale - 10) * 300) + (100 * (COUNT(d.course_code) * (1.0 + (0.1 * COUNT(s.student_id)))) + (50 * c.amount_of_assignments)))
GROUP BY t.bsn;

1 个答案:

答案 0 :(得分:1)

根据SQL标准,HAVING子句应该 AFTER GROUP BY;你的是以前。

您的密码:

SELECT 
        t.bsn
FROM 
        teachers t, designes d, students s, course c, teaches lg
WHERE 
        c.course_follower = s.class AND 
        t.bsn = lg.bsn AND 
        d.course_code = c.course_code AND 
        d.bsn = t.bsn AND 
        s.class = lg.class 
HAVING 
        t.salary = (2000 + (t.scale * 200) + ((t.scale - 10) * 300) + (100 * (COUNT(d.course_code) * (1.0 + (0.1 * COUNT(s.student_id)))) + (50 * c.amount_of_assignments)))
GROUP BY
        t.bsn;

预期:

SELECT 
        t.bsn
FROM 
        teachers t, designes d, students s, course c, teaches lg
WHERE 
        c.course_follower = s.class AND 
        t.bsn = lg.bsn AND 
        d.course_code = c.course_code AND 
        d.bsn = t.bsn AND 
        s.class = lg.class 
GROUP BY
        t.bsn
HAVING 
        t.salary = (2000 + (t.scale * 200) + ((t.scale - 10) * 300) + (100 * (COUNT(d.course_code) * (1.0 + (0.1 * COUNT(s.student_id)))) + (50 * c.amount_of_assignments)));

通用SQL示例 - http://www.w3schools.com/sql/sql_having.asp

PostgreSQL SQL示例 - https://www.postgresql.org/docs/current/static/tutorial-agg.html