如果其中一行包含一个为null的列,则合并两行

时间:2016-11-14 11:17:51

标签: mysql sql

我有一张这样的表:

cusstomerID; EMail, Telefon, Fax
2; s@l.com; 0123; NULL      
2; s@l.com; NULL; 456       
3, p@y.com; 01792494976; NULL       
3; p@y.com; NULL; 01792494977
4; a@c.com; 0167578252; NULL        
5; qr@g.com; 069-541111; NULL   
5; qr@g.com; NULL; 069-541222   
6; cv@gv.com; NULL; 0123456

预期结果:

cusstomerID; EMail, Telefon, Fax
2; s@l.com; 0123; 456
3, p@y.com; 01792494976; 01792494977
4; a@c.com; 0167578252; NULL        
5; qr@g.com; 069-541111; 069-541222 
6; cv@gv.com; NULL; 0123456

当客户有电话号码和传真号码时(当客户只有一个他/她只有一行时),我的数据库中的每个客户总共有2行:在第一行中,传真号码是空的,在第二个传真号码是空的:我怎么能把它放在一行?通过(我的)SQL

我只想update表 - 而不是创建新表:)

感谢您的支持!

2 个答案:

答案 0 :(得分:0)

为了使其成为可能,您必须加入表格才能根据值选择正确的字段。

SELECT cusstomerID, EMail, IFNULL(t1.Telefon, t2.Telefon), IFNULL(t1.Fax, t2.Fax)
FROM tablename t1 
JOIN tablename t2 ON t1.cusstomerID = t2.cusstomerID

要清理你的桌子,你可以这样做:

UPDATE FROM tablename t1, tablename t2
SET t1.Telefon = IFNULL(t1.Telefon, t2.Telefon)
[...]
WHERE t1.cusstomerID = t2.cusstomerID ;

DELETE FROM tablename 
WHERE ( Telefon IS NULL
OR Fax IS NULL ) 
AND cusstomerID IN ( 
    SELECT cusstomerID 
    FROM tablename 
    GROUP BY cusstomerID 
    HAVING COUNT(cusstomerID ) = 2
);

或者您可以使用CREATE TABLE AS语句创建新表并删除旧表。

CREATE TABLE tablename2 AS ( SELECT t1.customerssID, t1.EMail, IFNULL( t1.Telefon, t2.Telefon ) AS Telefon, IFNULL( t1.Fax, t2.Fax ) AS Fax

FROM tablename t1 JOIN tablename t2 ON t1.customerssID = t2.customerssID);

然后你可以DELETE旧表

DELETE tablename; 

重命名新的。

RENAME TABLE tablename2 tablename;

编辑:将MAXGROUP BY

一起使用

经过一些研究,我发现SO Post这使得jarlh回答正确。所以答案可能是:

CREATE TABLE tablename2 AS ( SELECT `cusstomerID`, `EMail`, MAX(`Telefon`), MAX(`Fax`)
FROM tablename
GROUP BY `cusstomerID` );

然后你可以DELETE旧表

DELETE tablename; 

重命名新的。

RENAME TABLE tablename2 tablename;

答案 1 :(得分:0)

update table1 t1,table1 t2 set t1.Telefon=t2.Telefon,t2.fax='delete' where t1.cusstomerID=t2.cusstomerID and t1.fax is not null and t2.Telefon is not null;

delete from table1 where fax='delete' and Telefon is not null;

更改表名并尝试。