Here are the tables:
CREATE TABLE [dbo].[Classes](
[ClassId] [int] NOT NULL,
[ClassName] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Classes] PRIMARY KEY CL
You mean something like this?
SELECT C.[ClassName], COUNT(*) AS 'Number of Students'
FROM [dbo].[Classes] AS C
INNER JOIN [dbo].[Students] AS S ON S.[ClassId] = C.[ClassId]
GROUP BY C.[ClassName]
Without having to add the group by
clause, you can do the following:
Create a function to get the students count:
go
CREATE FUNCTION [dbo].GetStudentsCountByClass(@classId int) RETURNS INT
AS BEGIN
declare @count as int
select @count = count(*) from STUDENTS
where ClassId = @classId
RETURN @count
END
then use it in your select
statement
SELECT * , dbo.GetStudentsCountByClass(ClassId) AS StudentsCount
FROM Classes
SELECT class.ClassId, count(student .StudentId) AS studentCount
FROM dbo.CLASSES class LEFT JOIN dbo.STUDENTS student ON (class.ClassId=student.ClassId)
GROUP BY class.ClassId
You need to do this -
SELECT C.ClassId, C.ClassName, count(S.StudentId) AS studentCount
FROM CLASSES C LEFT JOIN STUDENTS S ON (C.ClassId=S.ClassId)
GROUP BY C.ClassId, C.ClassName
select c.ClassId,C.ClassName,COUNT(*) [Number of students]
from Classes C,Students S
where c.ClassId=S.ClassId
group by C.ClassId,C.ClassName