Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner join with count and group by

I have 2 tables

Timetable :
pupil_id, staff_id, subject, lesson_id

Staff_info :
staff_id, surname

The timetable table contains 1000s of rows because each student's ID is listed under each period they do.

I want to list all the teacher's names, and the number of lessons they do (count). So I have to do SELECT with DISTINCT.

SELECT DISTINCT TIMETABLE.STAFF_ID,
                COUNT(TIMETABLE.LESSON_ID),
                STAFF.SURNAME
FROM STAFF
INNER JOIN TIMETABLE ON TIMETABLE.STAFF_ID = STAFF.STAFF_ID
GROUP BY TIMETABLE.STAFF_ID

However I get the error:

Column 'STAFF.SURNAME' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

like image 671
Robert Fakes Avatar asked Jun 06 '16 11:06

Robert Fakes


People also ask

Can I use inner join and GROUP BY together?

Using Group By with Inner JoinSQL Inner Join permits us to use Group by clause along with aggregate functions to group the result set by one or more columns.

Can we use count and GROUP BY together?

The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.

Can we use GROUP BY and count together in SQL?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

How do I count rows in a GROUP BY?

To count the number of rows, use the id column which stores unique values (in our example we use COUNT(id) ). Next, use the GROUP BY clause to group records according to columns (the GROUP BY category above). After using GROUP BY to filter records with aggregate functions like COUNT, use the HAVING clause.


1 Answers

This should do what you want:

SELECT s.STAFF_ID, COUNT(tt.LESSON_ID),
       s.SURNAME
FROM STAFF s INNER JOIN
     TIMETABLE tt
    ON tt.STAFF_ID = s.STAFF_ID
GROUP BY s.STAFF_ID, s.SURNAME;

Notes:

  • You don't need DISTINCT unless there are duplicates in either table. That seems unlikely with this data structure, but if a staff member could have two of the same lesson, you would use COUNT(DISTINCT tt.LESSON_ID).
  • Table aliases make the query easier to write and to read.
  • You should include STAFF.SURNAME in the GROUP BY as well as the id.
  • I have a preference for taking the STAFF_ID column from the table where it is the primary key.
  • If you wanted staff with no lessons, you would change the INNER JOIN to LEFT JOIN.
like image 89
Gordon Linoff Avatar answered Jan 04 '23 12:01

Gordon Linoff