简体   繁体   中英

SQL Not a GROUP BY expression

I'm still new to SQL.

I've got a query to count the number of students that attend a certain lecture and I've been trying to group the records by the lectureid so I don't have 10 records for the same lecture.

SELECT ATTENDANCESHEET.LECTUREID,TOPIC, (
       SELECT COUNT(STUDENTID) AS ATTENDANCE
           FROM ATTENDANCESHEET
           WHERE ATTENDANCESHEET.STUDENTID = LECTURE.STUDENTID
       )
FROM ATTENDANCESHEET,LECTURE
WHERE ATTENDANCESHEET.LECTUREID = LECTURE.LECTUREID
GROUP BY ATTENDANCESHEET.LECTUREID;

I'm getting the error "not a GROUP BY expression". Can someone help me, please?

The error is because you have a correlated query. The correlation clause (the where in the subquery) is using a column from the outer query that is not aggregated. In addition, you have a column topic that is not in the group by .

I believe the query you want is more simply written as:

select a.lectureid, count(*) as attendance
from attendancesheet a
group by a.lectureid;

I notice that you have topic in the select . That is also an issue. Perhaps you want:

select l.lectureid, l.topic, count(*) as attendance
from attendancesheet a join
     lecture l
     on a.lectureid = l.lectureid
group by l.lectureid;

Or, if you have studentid in lecture , perhaps:

select l.lectureid, l.topic, count(*) as attendance
from lecture l
group by l.lectureid;

EDIT:

The data structure doesn't make sense to me, but perhaps you need both keys for the join :

select l.lectureid, l.topic, count(*) as attendance
from attendancesheet a join
     lecture l
     on a.lectureid = l.lectureid and a.studentid = l.lectureid
group by l.lectureid;

to solve the issue of group by without knowing the expected result

SELECT ATTENDANCESHEET.LECTUREID,TOPIC, (
       SELECT COUNT(STUDENTID) AS ATTENDANCE
           FROM ATTENDANCESHEET
           WHERE ATTENDANCESHEET.STUDENTID = LECTURE.STUDENTID
       )
FROM ATTENDANCESHEET,LECTURE
WHERE ATTENDANCESHEET.LECTUREID = LECTURE.LECTUREID
GROUP BY ATTENDANCESHEET.LECTUREID,TOPIC,LECTURE.STUDENTID;   -- added the topic and studentid from lecture table

but I think what he's trying to do is

SELECT ATTENDANCESHEET.LECTUREID,TOPIC, count(LECTURE.STUDENTID) cntstudent
FROM ATTENDANCESHEET,LECTURE
WHERE ATTENDANCESHEET.LECTUREID = LECTURE.LECTUREID
GROUP BY ATTENDANCESHEET.LECTUREID,TOPIC

尝试通过:)将TOPIC添加到组中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM