Home > Back-end >  SQL Retrieve records with values on a field while also retrieving records that are null
SQL Retrieve records with values on a field while also retrieving records that are null

Time:10-02

I have this table of records and I want to retrieve the records that have values for one field while also retrieving the records that are null on the same field. sample table

CodePudding user response:

From the requirements posted it seems you want to quell rows that are null in Field 3 if there is another row that is non-null in Field 3 for the same values of Field1 and Field2

SELECT Field1, Field2, MAX(Field3) 
FROM t 
GROUP BY Field1, Field2

If you'll have multiple rows that have values and you want to keep them all you could do something with a union:

SELECT Field1, Field2, Field3 
FROM t
WHERE Field3 IS NOT NULL

UNION ALL

SELECT Field1, Field2, NULL
FROM t
GROUP BY Field1, Field2
HAVING COUNT(Field3) = 0

If gets you all the non nulls, plus all rows where counting Field3 results in 0 (i.e. field3 has only null for the pair)

  • Related