我有这张桌子:
Student - Id, FirstName, LastName, Age
Group - Id, Name
Student_Group - Student_Id, Group_Id
我需要找到最少的学生群体。我已经尝试了很多次。如果有人帮忙,我会很高兴。
答案 0 :(得分:2)
--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]
答案 1 :(得分:2)
您是否尝试过
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