insert和if语句来计算成绩

时间:2013-12-08 16:25:10

标签: sql sql-server tsql

基本上我正在创建一个学生测试软件,我的表结构的一部分如下:

RESULTS_TBL: QPaper_ID, Marks, Class, Subject, Grade, Student_ID [THIS TABLE STORES THE CALCULATED RESULTS BASED ON HIS PERFORMANCE]

ANSWERS_TBL: QPaper_ID, Marks, Class, Subject, Student_ID [THIS TABLE STORES ONLY THE CORRECT ANSWERS GIVEN BY THE STUDENTS AND THE MARKS FOR EACH QUESTION ]

我想主要计算成绩并将ANSWERS_TBL中的值插入到RESULTS_TBL中。以下是我的代码的一部分:

DECLARE @A_G INT, @B_G INT, @C_G INT, @D_G INT
SET @A_G = 40
SET @B_G = 30
SET @C_G = 10
INSERT INTO RESULTS ( QPaper_ID, Marks,Student_ID, Class, Grade)
select QPaper_ID, sum(Marks), Student_ID, Class,
case
when  sum(Marks) > @A_G then 'A'
when sum(Marks) between @B_G and @A_G then 'B'
when sum(Marks) between @C_G and @B_G then 'C'
else  'D'
END
from ANSWERS where QP_ID = 1000 and Login_ID = 'a'
GROUP BY QPaper_ID ,Marks, Student_ID, Class 

当我运行此查询时,ANSWERS中的所有行都被插入到我不想要的结果中。我只想要一个记录来计算每个问题的标记总和以及获得的等级。 BTW是正确的代码。

感谢

1 个答案:

答案 0 :(得分:0)

这是因为您将Marks放入GROUP BY子句中,这使得它返回所有记录(以及进行求和)。从GROUP BY

中删除它
DECLARE @A_G INT, @B_G INT, @C_G INT, @D_G INT
SET @A_G = 40
SET @B_G = 30
SET @C_G = 10
INSERT INTO RESULTS ( QPaper_ID, Marks,Student_ID, Class, Grade)
select QPaper_ID, sum(Marks), Student_ID, Class,
case
when  sum(Marks) > @A_G then 'A'
when sum(Marks) between @B_G and @A_G then 'B'
when sum(Marks) between @C_G and @B_G then 'C'
else  'D'
END
from ANSWERS where QP_ID = 1000 and Login_ID = 'a'
GROUP BY QPaper_ID, Student_ID, Class