I am working on a query that is fairly similar the following:
CREATE TABLE #test (a char(1), b char(1)) INSERT INTO #test(a,b) VALUES ('A',NULL), ('A','B'), ('B',NULL), ('B',NULL) SELECT DISTINCT a,b FROM #test DROP TABLE #test
The result is, unsurprisingly,
a b ------- A NULL A B B NULL
The output I would like to see in actuality is:
a b ------- A B B NULL
That is, if a column has a value in some records but not in others, I want to throw out the row with NULL for that column. However, if a column has a NULL value for all records, I want to preserve that NULL.
What's the simplest/most elegant way to do this in a single query?
I have a feeling that this would be simple if I weren't exhausted on a Friday afternoon.
In SQL, the DISTINCT clause doesn't ignore NULL values. So when using the DISTINCT clause in your SQL statement, your result set will include NULL as a distinct value.
SELECT column_names FROM table_name WHERE column_name IS NOT NULL; Query: SELECT * FROM Student WHERE Name IS NOT NULL AND Department IS NOT NULL AND Roll_No IS NOT NULL; To exclude the null values from all the columns we used AND operator.
If the COUNT DISTINCT function encounters NULL values, it ignores them unless every value in the specified column is NULL. If every column value is NULL, the COUNT DISTINCT function returns zero (0).
Try this:
select distinct * from test where b is not null or a in ( select a from test group by a having max(b) is null)
You can get the fiddle here.
Note if you can only have one non-null value in b
, this can be simplified to:
select a, max(b) from test group by a
;WITH CTE AS ( SELECT DISTINCT * FROM #test ) SELECT a,b FROM CTE ORDER BY CASE WHEN b IS NULL THEN 9999 ELSE b END ;
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