0

我在 Oracle 11g 数据库上。

询问:

SELECT s.id, s.grade_level, 
((1990+substr(sg.termid,1,2))||'-'||(1991+substr(sg.termid,1,2))) as  "School Year",
SUM(sg.earnedcrhrs) as "Credits"

FROM students s
JOIN storedgrades sg ON s.id = sg.studentid

WHERE s.schoolid = 109
AND s.id = '3466'
AND s.enroll_status = 0
AND sg.schoolid = 109

GROUP BY ROLLUP(s.id, s.grade_level, substr(sg.termid,1,2))
ORDER BY s.id, substr(sg.termid,1,2)

输出:

在此处输入图像描述

有没有办法可以编写我的查询,以便不产生第 5 行或第 6 行?每个学生我只需要一个小计(ID 列)。

4

2 回答 2

1

我得到了 Sanjay Misbra 和 Alan Beaulieu的 O'Reilly 的Mastering Oracle SQL的副本。根据他们的文档,我实际上以稍微不同的方式做到了这一点......

我将 GROUP BY 行从

GROUP BY ROLLUP(s.id, s.grade_level, substr(sg.termid,1,2))

GROUP BY s.id, s.grade_level, ROLLUP(substr(sg.termid,1,2))
于 2013-10-31T13:50:50.603 回答
1

这有点棘手。尝试这个:

SELECT s.id, s.grade_level, 
((1990+substr(sg.termid,1,2))||'-'||(1991+substr(sg.termid,1,2))) as  "School Year",
SUM(sg.earnedcrhrs) as "Credits"

FROM students s
JOIN storedgrades sg ON s.id = sg.studentid

WHERE s.schoolid = 109
AND s.id = '3466'
AND s.enroll_status = 0
AND sg.schoolid = 109

GROUP BY ROLLUP(s.id, (s.grade_level, substr(sg.termid,1,2)))
ORDER BY s.id, substr(sg.termid,1,2);

(不同的是我把s.grade_level, substr(sg.termid,1,2)子句GROUP BY放在括号里)

总的来说,我强烈推荐 Tim Hall 的这篇文章:Rollup, Cube and GROUPING functions

于 2013-10-30T20:50:50.230 回答