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

來源:互聯網
上載者:User

標籤:

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

使用 GROUP BY 的 WITH ROLLUP 字句可以檢索出更多的分組彙總資訊,它不僅僅能像一般的 GROUP BY 語句那樣檢索出各組的彙總資訊,還能檢索出本組類的整體彙總資訊。

下面我們的例子對比了普通的 GROUP BY 操作和有 WITH ROLLUP 子句的 GROUP BY 操作的不同:

查詢表的內容,是僱員的基礎資訊表:

 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 操作,可以按照部門和職位進行分組,計算每個部門,每個職位的工資平均值:

 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 語句,則可以輕鬆實現這個要求:

 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 語句對結果集進行排序,如果對返回的結果順序不滿意,需要應用程式獲得結果後在程式中進行排序。

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.