MySQL query to merge rows if Id is the same and display the highest corresponding value from other columns

MySQLMySQLi Database

For this, use aggregate function MAX() along with the GROUP BY clause. Let us first create a table −

mysql> create table DemoTable
(
   Id int,
   Value1 int,
   Value2 int,
   Value3 int,
   Value4 int
);
Query OK, 0 rows affected (0.61 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Id,Value4) values(100,30);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Id,Value1,Value2,Value3) values(100,20,60,40);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Id,Value2,Value3,Value4) values(100,90,100,110);
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+--------+--------+--------+--------+
| Id   | Value1 | Value2 | Value3 | Value4 |
+------+--------+--------+--------+--------+
| 100  | NULL   | NULL   | NULL   | 30     |
| 100  | 20     | 60     | 40     | NULL   |
| 100  | NULL   | 90     | 100    | 110    |
+------+--------+--------+--------+--------+
3 rows in set (0.00 sec)

Following is the query to merge rows if Id is the same and display the highest corresponding value from other columns −

mysql> select Id,max(Value1) as Value1,max(Value2) as Value2,max(Value3) as Value3,max(Value4) as Value4
from DemoTable
group by Id;

This will produce the following output −

+------+--------+--------+--------+--------+
| Id   | Value1 | Value2 | Value3 | Value4 |
+------+--------+--------+--------+--------+
| 100  | 20     | 90     | 100    | 110    |
+------+--------+--------+--------+--------+
1 row in set (0.00 sec)
raja
Published on 03-Oct-2019 06:40:53
Advertisements