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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With