如果ID相同,则MySQL查询合并行并显示其他列中的最高对应值
为此,将聚合函数MAX()
与GROUPBY子句一起使用。让我们首先创建一个表-
mysql> create table DemoTable ( Id int, Value1 int, Value2 int, Value3 int, Value4 int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(Id,Value4) values(100,30); mysql> insert into DemoTable(Id,Value1,Value2,Value3) values(100,20,60,40); mysql> insert into DemoTable(Id,Value2,Value3,Value4) values(100,90,100,110);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+------+--------+--------+--------+--------+ | 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)
以下是如果Id相同则合并行并显示其他列中最高对应值的查询-
mysql> select Id,max(Value1) as Value1,max(Value2) as Value2,max(Value3) as Value3,max(Value4) as Value4 from DemoTable group by Id;
这将产生以下输出-
+------+--------+--------+--------+--------+ | Id | Value1 | Value2 | Value3 | Value4 | +------+--------+--------+--------+--------+ | 100 | 20 | 90 | 100 | 110 | +------+--------+--------+--------+--------+ 1 row in set (0.00 sec)