Try this one:declare @testKey table (testId int, questionId int, answer varchar(1))Insert Into @testKeySelect 1, 1, 'A'Union All Select 1, 2, 'B'Union All Select 1, 3, 'A'declare @studentAnswers table (studentId int, testId int, questionId int, answer varchar(1))Insert Into @studentAnswersSelect 1, 1, 1, 'A'Union All Select 1, 1, 2, 'B'Union All Select 1, 1, 3, 'C'Union All Select 2, 1, 1, 'B'Union All Select 2, 1, 2, 'C'Union All Select 2, 1, 3, 'B'Union All Select 3, 1, 1, 'A'Union All Select 3, 1, 2, 'B'Union All Select 3, 1, 3, 'A' Select A.StudentId, A.testId, QCnt = count(*), Correct = sum(case when A.answer = B.answer then 1 else 0 end), Grade = convert(money,sum(case when A.answer = B.answer then 1 else 0 end))/convert(money,count(*))*100 From @studentAnswers as A Left Join @testKey as B On A.testId = B.testId and A.questionId = B.questionId Group By A.StudentId, A.TestId
Corey