行具有不同字段时列的最大值

时间:2014-05-23 12:40:24

标签: sql sql-server join

我写了以下sql查询

SELECT  ST.Roll, CR.Code, CR.Title, CR.Credits, SCH.ObtainedGPA, SCH.Grade
FROM [MIU_UCAM.1.0.1].[dbo].[StudentCourseHistory]  AS SCH
JOIN [MIU_UCAM.1.0.1].[dbo].[Student] AS ST ON SCH.StudentID = ST.StudentID
JOIN [MIU_UCAM.1.0.1].[dbo].[Course] AS CR ON SCH.CourseID = CR.CourseID AND SCH.VersionID = CR.VersionID

WHERE ST.Roll ='0914BPM00387'

返回结果如下

Roll            Code    Title                          Credits  ObtainedGPA  Grade

0914BPM00387    BPM216  Physiology Lab -                   1    4.00         A+
0914BPM00387    BPM217  Pharmaceutical Microbiology        3    2.25         C
0914BPM00387    BPM217  Pharmaceutical Microbiology        3    2.00         D 
0914BPM00387    BPM218  Pharmaceutical Microbiology Lab    1    3.50         A-

这里BPM217和BPM217是相同的,但它的ObtainedGrade是不同的,2.25和2.00和Grade也不同,C和D.现在我怎样才能得到只有列帽的最大值2.25。

2 个答案:

答案 0 :(得分:2)

如何在MAX上的ObtainedGPAMIN上使用GRADE

SELECT  ST.Roll, CR.Code, CR.Title, CR.Credits, MAX(SCH.ObtainedGPA), MIN(SCH.GRADE)
FROM [MIU_UCAM.1.0.1].[dbo].[StudentCourseHistory]  AS SCH
JOIN [MIU_UCAM.1.0.1].[dbo].[Student] AS ST ON SCH.StudentID = ST.StudentID
JOIN [MIU_UCAM.1.0.1].[dbo].[Course] AS CR ON SCH.CourseID = CR.CourseID AND SCH.VersionID = CR.VersionID
WHERE ST.Roll ='0914BPM00387'
GROUP BY ST.Roll, CR.Code, CR.Title, CR.Credits 

答案 1 :(得分:0)

尝试这样的事情。

SELECT ST.Roll, 
     CR.Code, 
     CR.Title, 
     CR.Credits, 
     (select MAX(SCH.ObtainedGPA)
          from StudenCourseHistory s
          where s.StudentID = ST.Student_ID
          and s.CourseID = CR.CourseID),
     SCH.Grade
FROM [MIU_UCAM.1.0.1].[dbo].[StudentCourseHistory]  AS SCH
JOIN [MIU_UCAM.1.0.1].[dbo].[Student] AS ST ON SCH.StudentID = ST.StudentID
JOIN [MIU_UCAM.1.0.1].[dbo].[Course] AS CR ON SCH.CourseID = CR.CourseID AND SCH.VersionID = CR.VersionID

WHERE ST.Roll ='0914BPM00387'