[轉]使用GROUP BY WITH ROLLUP改善統計性能

來源:http://blog.csdn.net/id19870510/article/details/6254358mysql

使用 GROUP BY 的 WITH ROLLUP 字句能夠檢索出更多的分組聚合信息,它不單單能像通常的 GROUP BY 語句那樣檢索出各組的聚合信息,還能檢索出本組類的總體聚合信息。sql

下面咱們的例子對比了普通的 GROUP BY 操做和有 WITH ROLLUP 子句的 GROUP BY 操做的不一樣:spa

查詢表的內容,是僱員的基礎信息表:.net

 1 <a href="http://lib.csdn.net/base/mysql" class='replace_word' title="MySQL知識庫" target='_blank' style='color:#df3434; font-weight:bold;'>MySQL</a>> select * from employee;  
 2   +------+--------+------+------+------+  
 3   | id | name | dep | pos | sal |  
 4   +------+--------+------+------+------+  
 5   | 1 | abcd | 01 | 01 | 1000 |  
 6   | 2 | eefs | 01 | 02 | 2000 |  
 7   | 3 | micro | 02 | 01 | 1500 |  
 8   | 4 | cathey | 02 | 02 | 3000 |  
 9   | 5 | amy | 03 | 01 | 2500 |  
10   | 6 | lily | 03 | 02 | 2200 |  
11   | 7 | bobo | 01 | 01 | 2000 |  
12   | 8 | gray | 01 | 02 | 1900 |  
13   | 9 | leon | 03 | 02 | 2900 |  
14   | 10 | sun | 02 | 02 | 1900 |  
15   +------+--------+------+------+------+  
16   10 rows in set (0.00 sec)  

普通的 GROUP BY 操做,能夠按照部門和職位進行分組,計算每一個部門,每一個職位的工資平均值:code

 1 mysql> select dep,pos,avg(sal) from employee group by dep,pos;
 2 +------+------+-----------+
 3 | dep | pos | avg(sal) |
 4 +------+------+-----------+
 5 | 01 | 01 | 1500.0000 |
 6 | 01 | 02 | 1950.0000 |
 7 | 02 | 01 | 1500.0000 |
 8 | 02 | 02 | 2450.0000 |
 9 | 03 | 01 | 2500.0000 |
10 | 03 | 02 | 2550.0000 |
11 +------+------+-----------+
12 6 rows in set (0.02 sec)

 

若是咱們但願再顯示部門的平均值和所有僱員的平均值,普通的 GROUP BY 語句是不能實現的,須要另外執行一個查詢操做,或者經過程序來計算。若是使用有 WITH ROLLUP 子句的 GROUP BY 語句,則能夠輕鬆實現這個要求:blog

 1 mysql> select dep,pos,avg(sal) from employee group by dep,pos with rollup;
 2 +------+------+-----------+
 3 | dep | pos | avg(sal) |
 4 +------+------+-----------+
 5 | 01 | 01 | 1500.0000 |
 6 | 01 | 02 | 1950.0000 |
 7 | 01 | NULL | 1725.0000 |
 8 | 02 | 01 | 1500.0000 |
 9 | 02 | 02 | 2450.0000 |
10 | 02 | NULL | 2133.3333 |
11 | 03 | 01 | 2500.0000 |
12 | 03 | 02 | 2550.0000 |
13 | 03 | NULL | 2533.3333 |
14 | NULL | NULL | 2090.0000 |
15 +------+------+-----------+
16 10 rows in set (0.00 sec)

須要注意的是,使用有 WITH ROLLUP 子句的 GROUP BY 語句時,不能再使用 ORDER BY 語句對結果集進行排序,若是對返回的結果順序不滿意,須要應用程序得到結果後在程序中進行排序。排序

相關文章
相關標籤/搜索