Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two rows in SQL

Tags:

sql

join

union

Assuming I have a table containing the following information:

FK | Field1 | Field2 ===================== 3  | ABC    | *NULL* 3  | *NULL* | DEF 

is there a way I can perform a select on the table to get the following

FK | Field1 | Field2 ===================== 3  | ABC    | DEF 

Thanks

Edit: Fix field2 name for clarity

like image 948
Jason Avatar asked May 31 '10 02:05

Jason


2 Answers

Aggregate functions may help you out here. Aggregate functions ignore NULLs (at least that's true on SQL Server, Oracle, and Jet/Access), so you could use a query like this (tested on SQL Server Express 2008 R2):

SELECT     FK,     MAX(Field1) AS Field1,     MAX(Field2) AS Field2 FROM     table1 GROUP BY     FK; 

I used MAX, but any aggregate which picks one value from among the GROUP BY rows should work.

Test data:

CREATE TABLE table1 (FK int, Field1 varchar(10), Field2 varchar(10));  INSERT INTO table1 VALUES (3, 'ABC', NULL); INSERT INTO table1 VALUES (3, NULL, 'DEF'); INSERT INTO table1 VALUES (4, 'GHI', NULL); INSERT INTO table1 VALUES (4, 'JKL', 'MNO'); INSERT INTO table1 VALUES (4, NULL, 'PQR'); 

Results:

FK  Field1  Field2 --  ------  ------ 3   ABC     DEF 4   JKL     PQR 
like image 122
Cheran Shunmugavel Avatar answered Sep 28 '22 10:09

Cheran Shunmugavel


There are a few ways depending on some data rules that you have not included, but here is one way using what you gave.

SELECT     t1.Field1,     t2.Field2 FROM Table1 t1     LEFT JOIN Table1 t2 ON t1.FK = t2.FK AND t2.Field1 IS NULL 

Another way:

SELECT     t1.Field1,     (SELECT Field2 FROM Table2 t2 WHERE t2.FK = t1.FK AND Field1 IS NULL) AS Field2 FROM Table1 t1 
like image 26
Dustin Laine Avatar answered Sep 28 '22 10:09

Dustin Laine