SQL组代码错误

时间:2018-05-28 09:54:14

标签: sql sql-server

在这个非常小的代码中,它一直告诉我“群组”周围的事情是错误的,但在我看来代码是非常正确的?

      SELECT
    grades.PERSON_ID, grades.GRADE, 
    students.PERSON_ID, students.ENROLL_PERIOD, students.FACULTY_ID
FROM  
    students 
INNER JOIN 
    grades ON students.PERSON_ID = grades.PERSON_ID 
WHERE 
    GRADE = '00' or
    GRADE ='-3' or
    GRADE ='U' or
    GRADE ='SY' or
    GRADE ='IA' or
    GRADE ='NI'
GROUP BY
    students.PERSON_ID
ORDER BY 
    students.PERSON_ID;

3 个答案:

答案 0 :(得分:0)

如果您没有使用带有列的聚合函数,则所有那些都在select中的应该在group by子句中。 Group by Means对列/列进行分组

SELECT
        grades.PERSON_ID, grades.GRADE, 
        students.PERSON_ID, students.ENROLL_PERIOD, students.FACULTY_ID
    FROM  
        students 
    INNER JOIN 
        grades ON students.PERSON_ID = grades.PERSON_ID 
    WHERE 
        GRADE = '00' or
        GRADE ='-3' or
        GRADE ='U' or
        GRADE ='SY' or
        GRADE ='IA' or
        GRADE ='NI'
    GROUP BY
        grades.PERSON_ID, grades.GRADE, 
        students.PERSON_ID, students.ENROLL_PERIOD, students.FACULTY_ID
    ORDER BY 
        students.PERSON_ID;

答案 1 :(得分:0)

您需要使用聚合函数来查找每个组的最高分数。 试试这个。

SELECT
    students.PERSON_ID, Max(grades.GRADE) As Max_GRADE
FROM  
    students 
INNER JOIN 
    grades ON students.PERSON_ID = grades.PERSON_ID 
WHERE 
    GRADE = '00' or
    GRADE ='-3' or
    GRADE ='U' or
    GRADE ='SY' or
    GRADE ='IA' or
    GRADE ='NI'
GROUP BY
    students.PERSON_ID
ORDER BY 
    students.PERSON_ID;

答案 2 :(得分:0)

我猜你根本不想要聚合。 。 。只是拥有其中一个等级的学生。

您的查询可以通过三种方式简化:

  • 表别名
  • IN
  • 在结果集中不包括PERSON_ID两次

所以,试着把它写成:

SELECT s.PERSON_ID, g.GRADE, s.ENROLL_PERIOD, s.FACULTY_ID
FROM students s INNER JOIN 
     grades g
     ON s.PERSON_ID = g.PERSON_ID 
WHERE g.GRADE IN ('00', '-3', 'U', 'SY', 'IA', 'NI')
ORDER BY s.PERSON_ID;

如果你想要每个PERSON_ID有一个任意行(正如你对GROUP BY的误用所示),你可以使用SQL Server技巧:

SELECT TOP (1) WITH TIES . . .
. . . 
ORDER BY RANK() OVER (PARTITION BY s.PERSON_ID ORDER BY (SELECT NULL))