先看实例:
有表B C1 c2 2005-01-01 1 2005-01-01 3 2005-01-02 5
要求的得到以下格式的数据 2005-01-01 4 2005-01-02 5 合计 9
试用一个Sql语句完成。
懒的去建表,就用现有的表来完成这个任务吧。
SELECT GROUPING(DEPT_NO) AS GROUP_DEPT_NO, GROUPING(COMP_NO) AS GROUP_COMP_NO, DECODE(GROUPING(DEPT_NO)||GROUPING(COMP_NO),'10',COMP_NO || '小计','11','总计') AS DESP, DEPT_NO,COMP_NO, COUNT(1) AS EMP_NUM FROM ASP_EMPLOYEE GROUP BY ROLLUP(COMP_NO,DEPT_NO)
运行结果如图:
ROLLUP和CUBE语句 Oracle的GROUP BY语句除了最基本的语法外,还支持ROLLUP和CUBE语句。如果是ROLLUP(A, B, C)的话,首先会对(A、B、C)进行GROUP BY,然后对(A、B)进行GROUP BY,然后是(A)进行GROUP BY,最后对全表进行GROUP BY操作。如果是GROUP BY CUBE(A, B, C),则首先会对(A、B、C)进行GROUP BY,然后依次是(A、B),(A、C),(A),(B、C),(B),(C),最后对全表进行GROUP BY操作。
GROUPING:
The GROUPING function distinguishes super aggregate rows from regular grouped rows. GROUP BY extensions such as ROLLUP and CUBE produce super aggregate rows where the set of all values is represented by null. Using the GROUPING function, you can distinguish a null representing the set of all values in a super aggregate row from a null in a regular row. The expr in the GROUPING function must match one of the expressions in the GROUP BY clause. The function returns a value of 1 if the value of expr in the row is a null representing the set of all values. Otherwise, it returns zero. The datatype of the value returned by the GROUPING function is Oracle NUMBER. |