0

I have a table like this:

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

Expected Outcome:

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

There are always 2 rows for every costumer in my data base when the customer has a telefon and a Fax Number (when the customer has only one of the 2 he/she has only one row): In the first row, the fax number is empty and in the second the telefone number is empty: how can I put it in one row? Via (my)SQL

I just want to update the table - not create a new one :)

Thanks for your support!

jarlh
  • 42,561
  • 8
  • 45
  • 63
AbsoluteBeginner
  • 485
  • 4
  • 13

2 Answers2

0

To make it possible, you have to join the table to be able to choose the right field depending on value.

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

And to clean your table, you can do something like this :

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
);

Or you can create a new table and delete the older with a CREATE TABLE AS statement.

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 );

Then you can DELETE the old table

DELETE tablename; 

And rename the new one.

RENAME TABLE tablename2 tablename;

EDIT : use MAX with GROUP BY

After some research, I found this SO Post which makes jarlh answer correct. So the answer can be :

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

Then you can DELETE the old table

DELETE tablename; 

And rename the new one.

RENAME TABLE tablename2 tablename;
Community
  • 1
  • 1
JoDev
  • 6,633
  • 1
  • 22
  • 37
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;

Change the table name and try it.

navintb
  • 129
  • 5