У меня есть эти таблицы:
Student - Id, FirstName, LastName, Age Group - Id, Name Student_Group - Student_Id, Group_Id
Мне нужно найти наименьшую группу студентов.Я пробовал много раз.Я был бы очень рад, если бы кто-нибудь помог.
Вы пытались сделать
SELECT top 1 g.name FROM group g INNER JOIN Student_group sg ON g.id = sg.Group_Id WHERE count(sg.student_id) >0 ORDER BY count(sg.student_id) GROUP BY sg.group_id
Если вы хотите также группы с 0 студентами, вы должны сделать
SELECT top 1 g.name FROM group g INNER JOIN Student_group sg ON g.id = sg.Group_Id ORDER BY count(sg.student_id) GROUP BY sg.group_id
--If you just need the group with the least members, --Group By and Count will work to find the Group with the least members --Then use select top 1 record and order by GroupCount Ascending SELECT TOP 1 Group_Id, COUNT(Group_Id) AS [GroupCount] FROM Student_Group GROUP BY Group_Id ORDER BY [GroupCount]