I have Following Tables in SQL Server Database:
(1) StudentMaster (StudentId, StudentName)
(2) SubjectMaster (SubjectId, SubjectName)
(3) AttendanceMaster (AttendanceId,StudentId,SubjectId,Attendance,Date)
Data in AttendanceMaster can be in Following format :
AttendanceMaster :
AttendanceId StudentId SubjectId Attendance Date
3001 33 1 P 1/1/2011
3001 57 2 P1 1/2/2011
3001 33 1 P 1/3/2011
3001 57 2 P2 1/4/2011
3001 33 1 P1 1/5/2011
I want to get SubjectWise Individual Attendance Details in Following Format:
StudentName SubjectName Total(P) Total(P1) Total(P2)
Ghanshyam Maths 90 10 5
John Maths 85 15 5
Ghanshyam Science 70 20 15
John Science 80 30 5
i tried following Query :
select StudentName, SubjectName,
(select count(*) from AttendanceMaster innerAM where innerAM.StudentId = StdM.StudentId and innerAM.SubjectId=SubM.SubjectId and innerAM.Attendance = 'P') as Total(P),
(select count(*) from AttendanceMaster innerAM where innerAM.StudentId = StdM.StudentId and innerAM.SubjectId=SubM.SubjectId and innerAM.Attendance = 'P1') as Total(P1),
(select count(*) from AttendanceMaster innerAM where innerAM.StudentId = StdM.StudentId and innerAM.SubjectId=SubM.SubjectId and innerAM.Attendance = 'P1') as Total(P2)
from AttendanceMaster AM inner join StudentMaster StdM on AM.StudentId = StdM.StudentId
inner join SubjectMaster SubM on AM.SubjectId = SubM.SubjectId
I got result but it gets too much time to execute..( about 5 to 6 minut )
so what can i do to decrease execution time...
and also is it right way to write a query to get Total(P),Toal(P1),Total(P2) ??
please specify other SQL Syntax
Thanks
Try this. If your query is still running slow, you need to check if there indexes on your table. If you table are large and there’re no indexes it still can be slow.
If columns
Attendancehas no values besides P, P1 and P2, to count total you need just addcount(*) as Total. If there are other values besides P, P1 and P2, there two ways. First – you can addAtM.Attendance in (‘P’, ‘P1’, ‘P2’) in where clause:
Or you can write it like this