Middle
SQL task: write a query to count the number of students for the teacher [name].
sobes.tech AI
Answer from AI
Suppose there are two tables: Teachers with columns TeacherID and Name, and Students with columns StudentID, Name, and TeacherID (foreign key to Teachers). To count the number of students for a teacher with a given name, you can use the following SQL query:
SELECT t.Name AS TeacherName, COUNT(s.StudentID) AS StudentCount
FROM Teachers t
LEFT JOIN Students s ON t.TeacherID = s.TeacherID
WHERE t.Name = 'Teacher_Name'
GROUP BY t.Name;
This query:
- Finds the teacher by name.
- Joins with the students table on
TeacherID. - Counts the number of students associated with that teacher.
If no teacher with such a name exists, the result will be empty. To consider multiple teachers with the same name, you can add an identifier or other conditions.