我必须显示每年平均成绩最低的学生的姓名。 我使用的表具有以下结构:
students
s_name | s_id | year
grades
s_id | grade
我尝试的一切都无法正常工作。
SELECT s.s_name FROM students s JOIN grades g ON s.s_id=g.s_id
GROUP BY s.s_name, s.year HAVING AVG(g.grade) = (SELECT MIN(AVG(g.grade)) FROM students s JOIN grades g ON s.s_id=g.s_id GROUP BY s.year)
答案 0 :(得分:1)
请尝试此查询:
CREATE TABLE #STUDENT
(
S_NAME VARCHAR(2),
S_ID INT IDENTITY(1,1) PRIMARY KEY,
YEAR INT
);
CREATE TABLE #GRADES
(
S_ID INT IDENTITY(1,1) PRIMARY KEY,
GRADE DECIMAL(3,2)
);
INSERT INTO #STUDENT VALUES('X1',2010);
INSERT INTO #STUDENT VALUES('X2',2010);
INSERT INTO #STUDENT VALUES('X3',2010);
INSERT INTO #STUDENT VALUES('X4',2010);
INSERT INTO #STUDENT VALUES('X5',2011);
INSERT INTO #STUDENT VALUES('X6',2011);
INSERT INTO #STUDENT VALUES('X7',2011);
INSERT INTO #STUDENT VALUES('X8',2012);
INSERT INTO #STUDENT VALUES('X8',2012);
INSERT INTO #STUDENT VALUES('X8',2012);
INSERT INTO #GRADES VALUES(6.5);
INSERT INTO #GRADES VALUES(6.9);
INSERT INTO #GRADES VALUES(7.3);
INSERT INTO #GRADES VALUES(6.0);
INSERT INTO #GRADES VALUES(7.9);
INSERT INTO #GRADES VALUES(8.1);
INSERT INTO #GRADES VALUES(6.6);
INSERT INTO #GRADES VALUES(7.2);
INSERT INTO #GRADES VALUES(7.6);
INSERT INTO #GRADES VALUES(8.2);
SELECT STUDENT_NAME, S_ID, YEAR, GRADE
FROM (
SELECT
FIRST_VALUE(ST.S_NAME) OVER (PARTITION BY ST.YEAR ORDER BY GR.GRADE ASC) AS 'STUDENT_NAME',
ST.S_ID, ST.YEAR, GR.GRADE,
ROW_NUMBER() OVER (PARTITION BY ST.YEAR ORDER BY GR.GRADE ASC) AS 'RANK'
FROM #STUDENT ST
INNER JOIN #GRADES GR ON ST.S_ID = GR.S_ID
)A
WHERE A.RANK = 1
DROP TABLE #STUDENT
DROP TABLE #GRADES