2013-04-11 159 views
2

我堅持這個錯誤:SQL查詢錯誤

Msg 8120, Level 16, State 1, Line 2 Column 'Subjects.off_CODE' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

我不知道什麼是錯的這個查詢。

use Enlistment 
go 

SELECT Subjects.off_CODE, Subjects.subj_CODE, Subjects.description, 
Subjects.unit, COUNT(Enlistment.off_CODE) FROM Enlistment, Subjects 
WHERE Subjects.off_CODE = 11315 
GROUP BY Enlistment.off_CODE 
+1

我想是這樣,你使用的是MSSQL ..你需要使用所有比總一個GROUP BY子句中。在這樣的條款的其他組的列將是'GROUP BY Subjects.off_CODE,Subjects.subj_CODE,主題.description, Subjects.unit' – Meherzad 2013-04-11 14:46:57

+3

您是否知道您正在桌子之間執行笛卡爾產品? – Lamak 2013-04-11 14:48:16

+0

謝謝你Meherzad。 – eaponz 2013-04-11 14:52:33

回答

1

如果選擇了列時,它必須出現在GROUP BY子句,除非它被包含在聚合函數(就像錯誤消息指出)。

use Enlistment 
go 

SELECT Subjects.off_CODE, Subjects.subj_CODE, Subjects.description, 
Subjects.unit, COUNT(Enlistment.off_CODE) FROM Enlistment, Subjects 
WHERE Subjects.off_CODE = 11315 
GROUP BY Subjects.off_CODE, Subjects.subj_CODE, Subjects.description, 
Subjects.unit 

所以,在你的榜樣,被包含在GROUP BY子句所選擇的唯一字段沒有爲Enlistment.off_CODE,因爲它是在聚合函數COUNT(使用COUNT( Enlistment.off_CODE))。所有其他字段必須包含在GROUP BY子句中。

0

你試試這個:

GROUP BY Enlistment.off_CODE, Subjects.off_CODE 

SELECT DISTINCT Subjects.off_CODE, Subjects.subj_CODE, Subjects.description, 
Subjects.unit, COUNT(Enlistment.off_CODE) FROM Enlistment, Subjects 
WHERE Subjects.off_CODE = 11315 
GROUP BY Enlistment.off_CODE, Subjects.off_CODE 

+0

仍然有同樣的錯誤。 – eaponz 2013-04-11 14:48:44

0

你告訴查詢到GROUP BY,你是不是選擇列。您將需要確保您選擇包含在GROUP BY字段中的列。

@ Question3CPO的會不同的是它包含在SELECT語句Subjects.subj_CODE工作,那就是在函數中可能不包含。