Mosh Feu
Mosh Feu

Reputation: 29249

Select count from another table to each row in result rows

Here are the tables:

CREATE TABLE [dbo].[Classes](
    [ClassId] [int] NOT NULL,
    [ClassName] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_Classes] PRIMARY KEY CLUSTERED 
(
    [ClassId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Students](
    [StudentId] [int] NOT NULL,
    [ClassId] [int] NOT NULL,
 CONSTRAINT [PK_Students] PRIMARY KEY CLUSTERED 
(
    [StudentId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Students]  WITH CHECK ADD  CONSTRAINT [FK_Students_Classes] FOREIGN KEY([ClassId])
REFERENCES [dbo].[Classes] ([ClassId])
GO
ALTER TABLE [dbo].[Students] CHECK CONSTRAINT [FK_Students_Classes]
GO

I want to get list of class, and each class - the number of student which belong to each class. How can I do this?

Upvotes: 9

Views: 28580

Answers (5)

Ali Kleit
Ali Kleit

Reputation: 3649

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

Upvotes: 1

Jitender Mahlawat
Jitender Mahlawat

Reputation: 3102

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

Upvotes: 0

Joe G Joseph
Joe G Joseph

Reputation: 24046

 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

Upvotes: 0

Kane
Kane

Reputation: 16802

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]

Upvotes: 3

Kshitij
Kshitij

Reputation: 8614

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

Upvotes: 23

Related Questions