Mysql group by with rollup, mysqlrollup

Source: Internet
Author: User

Mysql group by with rollup, mysqlrollup

1. Common group by operations can be grouped BY department and position to calculate the average salary of each department and position: mysql> select dep, pos, avg (sal) from employee group by dep, pos; + ------ + ----------- + | dep | pos | avg (sal) | + ------ + ----------- + | 01 | 01 | 1500.0000 | 01 | 02 | 1950.0000 | 02 | 01 | 1500.0000 | 02 | 02 | 2450.0000 | 03 | 01 | 2500.0000 | 03 | 02 | 2550.0000 | + ------ + ----------- + 6 rows in set (0.02 sec) 2. If we want to display the average value of the Department and the average value of all employees Average value. A common group by statement cannot be implemented. You need to perform another query operation or use a program to calculate the value. If you use a group by statement WITH a ROLLUP clause, you can easily implement this requirement: mysql> select dep, pos, avg (sal) from employee group by dep, pos with rollup; + ------ + ----------- + | dep | pos | avg (sal) | + ------ + ----------- + | 01 | 01 | 1500.0000 | 01 | 02 | 1950.0000 | 01 | NULL | 1725.0000 | 02 | 01 | 1500.0000 | 02 | 02 | | 2450.0000 | 02 | NULL | 2133.3333 | 03 | 01 | 2500.0000 | 03 | 02 | 2550.0000 | 03 | NULL | 2533.3333 | NULL | 2090.0000 | + ------ + ------ + ----------- + 10 rows in set (0.00 sec)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.