首页 > 数据库 > Oracle > 分析函数——rollup
原文出处(http://www.itpub.net/showthread.php?threadid=704960&pagenumber=)
有一张表test 如下, (NO 学生编号 ,cj 成绩)
NO name KM CJ
001 张三 语文 80
001 张三 数学 86
001 张三 英语 75
002 李四 语文 78
002 李四 数学 85
002 李四 英语 78
写了以下语句来算每项个科目的总分,
select decode(grouping(name),1,'总分',name) 姓名,
sum(decode(km, '数学',cj,0)) 数学,
sum(decode(km, '英语',cj,0)) 英语,
sum(decode(km, '语文',cj,0)) 语文,
sum(cj) 总成绩
from test group by rollup(name)
结果如下:
姓名 数学 英语 语文 总成绩
李四 85 78 78 241
张三 86 75 80 241
总分 171 153 158 482
问题是:现在要在以上结果的姓名后,加一列编号,
这样用rollup 要怎么写??
首先要熟悉grouping,rollup的含义,引用zhouwf0726关于分析函数的文章(http://www.itpub.net/608107.html)的一段话。
grouping函数判断是否合计列,如果是统计列则为1。
/*理解rollup
select a, b, c, sum( d )
from t
group by rollup(a, b, c);
等效于
select * from (
select a, b, c, sum( d ) from t group by a, b, c
union all
select a, b, null, sum( d ) from t group by a, b
union all
select a, null, null, sum( d ) from t group by a
union all
select null, null, null, sum( d ) from t
)
*/
这样就能很好的理解nyfor的回答了
select decode(grouping(name),1,'总分',name) 姓名,
decode(grouping(name),1,null,no) no,
sum(decode(km, '数学',cj,0)) 数学,
sum(decode(km, '英语',cj,0)) 英语,
sum(decode(km, '语文',cj,0)) 语文,
sum(cj) 总成绩
from test group by rollup((name,no))--注意这的处理
另一篇类似的文章http://www.itpub.net/706398.html
[@more@]来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/7659204/viewspace-897381/ ,如需转载,请注明出处,否则将追究法律责任。