我是SQL的新手并遇到这个问题:我必须检查每个学生是否都有成绩(1-10)。如果学生错过了成绩,我必须插入。但是没有学生应该有相同年级的副本 - 他们应该只有一次。
我所做的就是向所有学生展示他们的成绩:
SELECT CONCAT(studentdata.FirstName,studentdata.LastName) AS 'Name', grade.Grade
FROM studentdata
CROSS JOIN grade
WHERE studentdata.Id = grade.IdStudent
ORDER BY Name
答案 0 :(得分:2)
如果您的表gradelevels
只有一列(Grade
),可能的等级值(1,2,3,...,10),您可以这样做:
INSERT INTO grade
SELECT
studentdata.Id AS IdStudent,
gradelevels.Grade AS Grade
FROM studentdata -- Get all the students,
CROSS JOIN gradelevels -- one time for each possible grade.
LEFT JOIN grade ON
-- Now we will know what (student, grade) combinations have an entry in grade.
studentdata.Id = grade.IdStudent AND gradelevels.Grade = grade.Grade
WHERE grade.IdStudent IS NULL -- Only take the rows where there isnt already a grade.
如果您不想拥有包含等级的特定表格,则只需将CROSS JOIN gradelevels
替换为:
CROSS JOIN (SELECT Grade FROM grade GROUP BY Grade) gradelevels
SELECT
将为您提供所有使用的成绩,因此如果某些成绩未用于任何学生,则不会插入。
我建议您在表格IdStudent
Grade
和Grade
上设置唯一索引(或将其作为主键),以确保没有学生两次获得相同的成绩
答案 1 :(得分:2)
您可以使用此查询查看所有有或没有成绩的学生:
Select CONCAT(sd.FirstName,sd.LastName) AS 'Name', grade.Grade
from studentdata sd
left outer join grade
on sd.Id = grade.IdStudent
如果你只能看到没有成绩的学生:
Select CONCAT(sd.FirstName,sd.LastName) AS 'Name', grade.Grade
from studentdata sd
left outer join grade
on sd.Id = grade.IdStudent
WHERE ISNULL(grade.Grade, -1000) = -1000
最后插入默认等级" 5":
insert into grade (id, grade)
Select CONCAT(sd.FirstName,sd.LastName) AS 'Name', isnull(grade.Grade, 5) as Grade
from studentdata sd
left outer join grade
on sd.Id = grade.IdStudent
WHERE ISNULL(grade.Grade, -1000) = -1000
由于您的成绩表似乎包含所有作业的所有成绩,您想要添加到where语句," andgrade.assigmentid =