我有以下表格
|Id| Title |
|1 |Lesson 1|
|2 |Lesson 2|
|3 |Lesson 3|
|4 |Lesson 4|
|5 |Lesson 5|
|6 |Lesson 6|
|Id|Lesson|Score|
|1 | 2 | 75 |
|2 | 3 | 30 |
|3 | 3 | 90 |
我想获得不同的课程但只有最大值,所以结果将是:
|Lesson|Score|
| 2 | 75 |
| 3 | 90 |
所以在下面的查询中,我在哪里放DISTINCT和MAX来实现这样的结果?
SELECT LessonConclusionData.Lesson, LessonConclusionData.Score
FROM LessonConclusionData INNER JOIN Lessons ON LessonConclusionData.Lesson = Lessons.Id
答案 0 :(得分:1)
按课程分组并获得MAX(分数)。
SELECT LessonConclusionData.Lesson, MAX(LessonConclusionData.Score) as MaxScore
FROM LessonConclusionData
INNER JOIN Lessons ON LessonConclusionData.Lesson = Lessons.Id
GROUP BY LessonConclusionData.Lesson;
答案 1 :(得分:1)
SELECT ID,MAX(SCORE)
FROM tablename
GROUP BY ID`
答案 2 :(得分:1)
假设SQL Server版本> = 2005,此代码(使用公用表表达式)将产生所需的结果:
; with x as (
select Lesson, max(Score) Score
from LessonConclusionData
group by Lesson
)
select y.* from x join LessonConclusionData y on x.Lesson = y.Lesson and x.Score = y.Score
order by y.Lesson
如果您需要显示课程名称,您应该加入课程表,如下所示:
; with x as (
select Lesson, max(Score) Score
from LessonConclusionData
group by Lesson
)
select y.*, Lessons.Title from x join LessonConclusionData y on x.Lesson = y.Lesson and x.Score = y.Score
right join Lessons on x.Lesson = Lessons.Id
order by y.Lesson
我选择了RIGHT JOIN而不是返回所有课程的结果,即使对于那些没有LessonConclusionData的人也是如此。如果您只想返回存在详细信息的课程,请使用INNER JOIN。