使用聚合函数而不在SELECT中包含它们

时间:2015-03-23 21:17:38

标签: sql sql-server greatest-n-per-group

我们说我有一个包含学校课程的数据库,我想找到学生身份证号码最低的一年级,三年级和五年级,但我只想在结果中返回ClassID设置(不是学号)。

编辑:我意识到现在这不是我真正问题的完美模型。更新它以更正确地反映问题。

我发现这样做的唯一方法如下:

SELECT 
    ClassID
FROM 
    Classes 
INNER JOIN
    Students ON Classes.ClassID = Students.ClassID
WHERE 
    Classes.Grade IN (1, 3, 5)
GROUP BY 
    Classes.ClassID
HAVING 
    MIN(StudentID) = MIN(StudentID)

返回相同的ClassID列表,如下所示:

 SELECT 
        ClassID,
        MIN(StudentID)
    FROM 
        Classes 
    INNER JOIN
        Students ON Classes.ClassID = Students.ClassID
    WHERE 
        Classes.Grade IN (1, 3, 5)
    GROUP BY 
        Classes.ClassID

这似乎有效,但对我来说看起来很有趣。这是唯一的方法吗?

2 个答案:

答案 0 :(得分:1)

“获得5年级最低学生成绩,然后告诉我他/她在哪个班级,有2个步骤。”所以我认为嵌套查询可能是最简单的事情,例如:

Select ClassId 
From Students
Join 
    ( Select Classes.Grade, Min(StudentId) as StudentId
        From Classes 
        Join Students ON Classes.ClassID = Students.ClassID
        Where Classes.Grade  in (1, 3, 5)
        Group By Classes.Grade 
        ) LowestStudentIdPerGrade
    On Students.StudentId = LowestStudentIdPerGrade.StudentId

答案 1 :(得分:1)

如果您希望三个班级中的学生ID最低,请使用order bytop

SELECT TOP 1 Classes.ClassID
FROM Classes INNER JOIN
     Students
     ON Classes.ClassID = Students.ClassID
WHERE Classes.Grade IN (1, 3, 5)
ORDER BY StudentId ASC;

如果您希望此信息每个课程,请使用row_number()

SELECT ClassId, Grade
FROM (SELECT Classes.ClassID, Classes.Grade,
            ROW_NUMBER() OVER (PARTITION BY Classes.ClassID ORDER BY StudentId ASC) as seqnum
     FROM Classes INNER JOIN
          Students
          ON Classes.ClassID = Students.ClassID
     WHERE Classes.Grade IN (1, 3, 5)
    ) c
WHERE seqnum = 1;

您不需要group by