For this, you can use GROUP BY clause. To find maximum value, use MAX() function. Let us first create a table −
mysql> create table DemoTable1804 ( Id int, Marks1 int, Marks2 int, Marks3 int ); Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1804 values(1,56,89,34); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1804 values(1,98,null,94); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1804 values(2,34,45,78); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1804 values(2,null,67,null); Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1804;
This will produce the following output −
+------+--------+--------+--------+ | Id | Marks1 | Marks2 | Marks3 | +------+--------+--------+--------+ | 1 | 56 | 89 | 34 | | 1 | 98 | NULL | 94 | | 2 | 34 | 45 | 78 | | 2 | NULL| 67 | NULL | +------+--------+--------+--------+ 4 rows in set (0.00 sec)
Here is the query for rows concatenation and finding maximum value −
mysql> select Id,max(Marks1),max(Marks2),max(Marks3) from DemoTable1804 group by Id;
This will produce the following output −
+------+-------------+-------------+-------------+ | Id | max(Marks1) | max(Marks2) | max(Marks3) | +------+-------------+-------------+-------------+ | 1 | 98 | 89 | 94 | | 2 | 34 | 67 | 78 | +------+-------------+-------------+-------------+ 2 rows in set (0.00 sec)