0、建表及插入測試數據
1、GROUP BY子句的增強
A、GROUPING SETS
--------理解grouping sets
select a, b, c, sum( d ) from t
group by grouping sets ( a, b, c )
等效於
select * from (
select a, null, null, sum( d ) from t group by a
union all
select null, b, null, sum( d ) from t group by b
union all
select null, null, c, sum( d ) from t group by c
)
B、ROLLUP
--------理解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
)
C、CUBE
--------理解cube
select a, b, c, sum( d ) from t
group by cube( a, b, c)
等效於
select a, b, c, sum( d ) from t
group by grouping sets(
( a, b, c ),
( a, b ), ( a ), ( b, c ),
( b ), ( a, c ), ( c ),
() )
D、GROUPING函數
從上面的結果中我們很容易發現,每個統計數據所對應的行都會出現null,如何來區分到底是根據那個字段做的彙總呢,grouping函數判斷是否合計列!
2、OVER()函數的使用
A、RANK()、DENSE_RANK() 、ROW_NUMBER()、CUME_DIST()、MAX()、AVG()
B、SUM()
C、LAG(COL,n,default)、LEAD(OL,n,default) --取前後邊N條數據
D、FIRST_VALUE()、LAST_VALUE()