在尝试学习子查询时,我希望获得一些帮助,但是我仍在努力争取更多的“复杂”位。
这是示例,带有三个表。
dbo.Teacher
StaffID | FirstName | LastName
dbo.Modules
StaffID | ModuleID | ModuleDesc
dbo.StudentModule
ModuleID | OverallMark
显然有更多的行,但这与我的问题有关。
现在,我需要在ANY模块上显示每位老师给的最低分。 因此,基本上,在任何模块上,老师(通常)给所有学生的最低总体得分。
然后我需要显示所有信息,
StaffID | FirstName | LastName | ModuleID | ModuleDesc | OverallMark
这种关系是显而易见的(StaffID-StaffID | ModuleID-ModuleID)
SELECT m.ModuleID ,
m.ModuleDescription ,
t.FirstName ,
t.Surname ,
t.StaffID ,
(
SELECT MIN(sm.OverallMark)
FROM dbo.StudentModule sm
WHERE m.ModuleID = sm.ModuleID AND m.StaffID = t.StaffID
) AS OverallMark
FROM dbo.Modules m
JOIN dbo.Teacher t ON m.StaffID = t.StaffID
ORDER BY
(
SELECT MIN(sm.OverallMark) FROM dbo.StudentModule sm WHERE m.ModuleID =
sm.ModuleID AND m.StaffID = t.StaffID
) ASC
答案 0 :(得分:1)
尝试一下
SELECT StaffID, FirstName, LastName, ModuleID, ModuleDesc, OverallMark
FROM (
SELECT t.StaffID, t.FirstName, t.LastName, m.ModuleID, m.ModuleDesc, sm.OverallMark
, ROW_NUMBER() OVER(PARTITION BY m.StaffID ORDER BY sm.OverallMark) AS TheRank
FROM Teacher t
JOIN Modules m ON m.StaffID = t.StaffID
JOIN StudentModule sm ON sm.ModuleID = m.ModuleID
) a
WHERE TheRank = 1
答案 1 :(得分:-1)
尝试一下:
SELECT
t.FirstName
, t.LastName
, MIN( sm.OverallMark ) AS LowestMark
FROM dbo.Teacher t
INNER JOIN dbo.Module m
ON t.StaffID = m.StaffID
INNER JOIN dbo.StudentModule sm
ON m.ModuleID = sm.ModuleID
GROUP BY
t.FirstName, t.LastName
ORDER BY
t.FirstName, t.LastName;