Problem Statement:-
There are students, courses and courses are registered to students. I want to get a list of student and their courses by months.
Solution:-
Create table Course:-
–CREATE TABLE [dbo].[Course](
[CourseID] [int] IDENTITY(1,1) NOT NULL,
[CourseName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED
(
[CourseID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
— Create table Student
CREATE TABLE [dbo].[Student](
[StudentID] [int] IDENTITY(1,1) NOT NULL,
[StudentName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Student] 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]
— Create table StudentCourse
CREATE TABLE [dbo].[StudentCourse](
[StudentCourseID] [int] IDENTITY(1,1) NOT NULL,
[StudentID] [int] NOT NULL,
[CourseID] [int] NOT NULL,
[RegDate] [smalldatetime] NOT NULL,
CONSTRAINT [PK_StudentCourse] PRIMARY KEY CLUSTERED
(
[StudentCourseID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
—- Insert data into Course
–INSERT INTO Course ( CourseName ) VALUES (‘Maths’)
–INSERT INTO Course ( CourseName ) VALUES (‘Physics’)
–INSERT INTO Course ( CourseName ) VALUES (‘Computer’)
—- Insert data into Student
–INSERT INTO Student( StudentName )VALUES (‘Faisal’)
–INSERT INTO Student( StudentName )VALUES (‘Irfan’)
–INSERT INTO Student( StudentName )VALUES (‘Haris’)
—- Insert data into Student Course
–INSERT INTO dbo.StudentCourse( StudentID, CourseID, RegDate )VALUES ( 1, 1, ’07/05/2014′ )
–INSERT INTO dbo.StudentCourse( StudentID, CourseID, RegDate )VALUES ( 1, 2, ’07/05/2014′ )
–INSERT INTO dbo.StudentCourse( StudentID, CourseID, RegDate )VALUES ( 2, 1, ’08/05/2014′ )
–INSERT INTO dbo.StudentCourse( StudentID, CourseID, RegDate )VALUES ( 2, 3, ’09/05/2014′ )
–INSERT INTO dbo.StudentCourse( StudentID, CourseID, RegDate )VALUES ( 3, 2, ’09/05/2014′ )
— Following is the query to get the required results.
SELECT * FROM (
select
S.StudentName,
C.CourseName,
MONTH(SC.RegDate) RegMonth
from
dbo.Student S
INNER JOIN dbo.StudentCourse SC ON S.StudentID = SC.StudentID
INNER JOIN dbo.Course C ON SC.CourseID = C.CourseID
)a
pivot (count(a.CourseName) for a.StudentName in ([Faisal],[Irfan],[Haris])) as NoofCoursesPErStudent
In the above query i am taking count of CourseName field and showing each student name as a separate column as in ([Faisal],[Irfan],[Haris]);
Result :-