SQL不正确的JOIN和条件比较值

时间:2014-04-12 04:44:22

标签: sql sql-server join union

我正在做这些陈述,并且通过获得正确的最小值和最大值范围来解决问题。

SELECT 
C.CourseId, 
C.GradeValue MinGradeValue,
isnull(min(m.GradeValue)-1,100) MAxGradeValue,
L.LetterGrade ,
L.[Description] 
    FROM CourseGrade C

    LEFT JOIN LetterGrades L
    ON C.LetterGradedId=L.LetterGradeId 

    LEFT JOIN CourseGrade m
    ON m.LetterGradedId=L.LetterGradeId  AND m.GradeValue > C.GradeValue

    GROUP BY
    C.CourseId, 
    C.GradeValue, L.LetterGrade ,
    L.[Description];

enter image description here

这是正确的范围:

enter image description here

2 个答案:

答案 0 :(得分:1)

您的上一次加入需要在CourseID上

SELECT 
    C.CourseId, 
    C.GradeValue MinGradeValue,
    isnull(min(m.GradeValue)-1,100) MAxGradeValue,
    L.LetterGrade ,
    L.[Description] 
FROM CourseGrade C

    LEFT JOIN LetterGrades L
        ON C.LetterGradedId=L.LetterGradeId 

    LEFT JOIN CourseGrade m
        ON m.CourseId=c.CourseId
        AND m.GradeValue > C.GradeValue

GROUP BY
    C.CourseId, 
    C.GradeValue, L.LetterGrade ,
    L.[Description];

答案 1 :(得分:0)

看看

  LEFT JOIN CourseGrade m
    ON m.LetterGradedId=L.LetterGradeId  AND m.GradeValue > C.GradeValue

第一个字符串 c.GradeValue = 0 这个条件是假的

m.GradeValue > C.GradeValue

因此你在min(m.GradeValue)中得到null,你的isnull返回100