How to correctly use WITH ROLLUP in MySQL?


The syntax is as follows to use WITH ROLLUP −

select yourColumnName1,sum(yourColumnName2) from yourTableName
 group by yourColumnName1 with rollup;

Let us first create a table −

mysql> create table DemoTable1622
    -> (
    -> EmployeeCountryName varchar(20),
    -> EmployeeSalary int
    -> );
Query OK, 0 rows affected (0.44 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1622 values('US',4500);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1622 values('UK',1500);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1622 values('AUS',1700);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1622 values('UK',1900);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1622 values('US',3900);
Query OK, 1 row affected (0.42 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1622;

This will produce the following output −

+---------------------+----------------+
| EmployeeCountryName | EmployeeSalary |
+---------------------+----------------+
| US                  |           4500 |
| UK                  |           1500 |
| AUS                 |           1700 |
| UK                  |           1900 |
| US                  |           3900 |
+---------------------+----------------+
5 rows in set (0.00 sec)

Here is the query to correctly use WITH ROLLUP in MySQL −

mysql> select EmployeeCountryName,sum(EmployeeSalary) from DemoTable1622
    -> group by EmployeeCountryName with rollup;

This will produce the following output −

+---------------------+---------------------+
| EmployeeCountryName | sum(EmployeeSalary) |
+---------------------+---------------------+
| AUS                 |                1700 |
| UK                  |                3400 |
| US                  |                8400 |
| NULL                |               13500 |
+---------------------+---------------------+
4 rows in set (0.02 sec)
raja
Published on 08-Nov-2019 11:13:57
Advertisements