2016-12-28 52 views
0

我已經創建了下面的查詢,但是當我運行它時,我在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; 
+5

'集團BY'到來之前'HAVING'。但是,查詢還存在其他大問題。您正在創建這四張表的笛卡爾積。作爲一個經驗法則,逗號應該永遠不會被放在'FROM'子句中(這種做法現在已被棄用** 25年**)。改用顯式的'JOIN'語法。 – Siyual

回答

1

根據SQL標準HAVING條款應該來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

相關問題