mysql – 将重复的行合并为一行
作者:互联网
MySQL中有一个如下表:
+-----+------+-------+-----------+----------+---------+
| #id | NAME | empid | c_lan | Java_lan | Dot_lan |
+-----+------+-------+-----------+----------+---------+
| 1 | raju | 111 | yes | NULL | NULL |
| 1 | raju | 111 | NULL | NO | NULL |
| 1 | raju | 111 | NULL | NULL | na |
| 2 | ramu | 222 | yes | NULL | NULL |
| 2 | ramu | 222 | NULL | NO | NULL |
| 2 | ramu | 222 | NULL | NULL | na |
+-----+------+-------+-----------+----------+---------+
如何编写查询以获得以下结果?
+-----+------+-------+-------+----------+---------+
| #id | name | empid | c_lan | Java_lan | Dot_lan |
+-----+------+-------+-------+----------+---------+
| 1 | raju | 111 | yes | no | na |
| 2 | ramu | 222 | yes | no | na |
+-----+------+-------+-------+----------+---------+
解决方法:
SELECT id, name, empid
MAX(c_lan) AS c_lan,
MAX(Java_lan) AS Java_lan,
MAX(Dot_lan) AS Dot_lan
FROM tbl
GROUP BY id, name, empid;
如果你真的不需要NO而不是NO,那么添加LOWER(…).
编辑.
我假设一个类似的表结构
CREATE TABLE Lans (
// id NAME empid c_lan Java_lan Dot_lan
id SMALLINT UNSIGNED NOT NULL,
name VARCHAR(50) NOT NULL,
empid SMALLINT UNSIGNED NOT NULL,
c_lan VARCHAR(10) NULL,
java_lan VARCHAR(10) NULL,
dot_lan VARCHAR(10) NULL,
PRIMARY KEY(id, name)
) ENGINE=InnoDB;
标签:mysql,duplication 来源: https://codeday.me/bug/20190806/1603308.html