Group By Rollup抑制额外的数据行

时间:2013-10-30 19:10:28

标签: sql oracle null group-by rollup

我在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)

输出:

enter image description here

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

我能够通过Sanjay Misbra& amp;获得O'Reilly的掌握Oracle SQL 的副本。 Alan Beaulieu。在他们的文档之后,我实际上以稍微不同的方式做到了这一点......

我从

更改了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))