Call aggregate function in sort order with MySQL

MySQLMySQLi Database

For this, use GROUP_CONCAT() along with ORDER BY clause. Let us first create a table −

mysql> create table DemoTable1588
   -> (
   -> StudentId int,
   -> StudentFirstName varchar(20),
   -> StudentMarks int
   -> );
Query OK, 0 rows affected (0.49 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1588 values(110,'Bob',78);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1588 values(101,'Sam',78);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1588 values(105,'Mike',78);
Query OK, 1 row affected (0.26 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1588;

This will produce the following output −

+-----------+------------------+--------------+
| StudentId | StudentFirstName | StudentMarks |
+-----------+------------------+--------------+
|       110 | Bob              |           78 |
|       101 | Sam              |           78 |
|       105 | Mike             |           78 |
+-----------+------------------+--------------+
3 rows in set (0.00 sec)

Here is the query to call aggregate function in sort order −

mysql> select group_concat(StudentFirstName order by StudentId separator '--') from DemoTable1588
   -> group by StudentMarks;

This will produce the following output −

+------------------------------------------------------------------+
| group_concat(StudentFirstName order by StudentId separator '--') |
+------------------------------------------------------------------+
| Sam--Mike--Bob                                                   |
+------------------------------------------------------------------+
1 row in set (0.04 sec)
raja
Published on 16-Dec-2019 06:43:01
Advertisements