Oracle的group by除了基本用法以外,还有3种扩展用法,分别是rollup、cube、grouping sets。 1 rollup 假设有一个表test,有A、B、C、D、E5列。 如果使用group by rollup(A,B,C),首先会对(A、B、C)进行GROUP BY,然后对(A、B)进行GROUP BY,然后是(A)进行GROUP BY,最后对全表进行GROUP BY操作。roll up的意思是“卷起”,这也可以帮助我们理解group by rollup就是对选择的列从右到左以一次少一列的方式进行grouping直到所有列都去掉后的grouping(也就是全表grouping),对于n个参数的rollup,有n+1次的grouping。以下2个sql的结果集是一样的: Select A,B,C,sum(E) from test group by rollup(A,B,C) 与 Select A,B,C,sum(E) from test group by A,B,C union all Select A,B,null,sum(E) from test group by A,B union all Select A,null,null,sum(E) from test group by A union all Select null,null,null,sum(E) from test
2 cube cube的意思是立方,对cube的每个参数,都可以理解为取值为参与grouping和不参与grouping两个值的一个维度,然后所有维度取值组合的集合就是grouping的集合,对于n个参数的cube,有2^n次的grouping。如果使用group by cube(A,B,C),,则首先会对(A、B、C)进行GROUP BY,然后依次是(A、B),(A、C),(A),(B、C),(B),(C),最后对全表进行GROUP BY操作,一共是2^3=8次grouping。同rollup一样,也可以用基本的group by加上结果集的union all写出一个与group by cube结果集相同的sql: Select A,B,C,sum(E) from test group by cube(A,B,C); 与 Select A,B,C,sum(E) from test group by A,B,C union all Select A,B,null,sum(E) from test group by A,B union all Select A,null,C,sum(E) from test group by A,C union all Select A,null,null,sum(E) from test group by A union all Select null,B,C,sum(E) from test group by B,C union all Select null,B,null,sum(E) from test group by B union all Select null,null,C,sum(E) from test group by C union all Select null,null,null,sum(E) from test; 3 grouping sets grouping sets就是对参数中的每个参数做grouping,也就是有几个参数做几次grouping,例如使用group by grouping sets(A,B,C),则对(A),(B),(C)进行group by,如果使用group by grouping sets((A,B),C),则对(A,B),(C)进行group by。甚至grouping by grouping set(A,A)都是语法允许的,也就是对(A)进行2次group by,grouping sets的参数允许重复 |