当 ID 相同时合并行并显示其他列中相应的最高值
为此,请使用聚合函数 MAX() 和 GROUP BY 子句。首先,我们创建一个表 -
mysql> create table DemoTable ( Id int, Value1 int, Value2 int, Value3 int, Value4 int ); Query OK, 0 rows affected (0.61 sec)
使用 insert 命令在表中插入一些记录 -
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)
使用 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)
广告