Reputation: 7347
Lets say I have a table with 2 columns (a, b) with following values:
a b
--- ---
1 5
1 NULL
2 NULL
2 NULL
3 NULL
My desired output:
a
---
2
3
I want to select only those distinct values from column a for which every single occurrence of this value has NULL in column b. Therefore from my desired output, "1" won't come in because there is a "5" in column b even though there is a NULL for the 2nd occurrence of "1".
How can I do this using a TSQL query?
Upvotes: 1
Views: 2992
Reputation: 115530
Two more ways to do this:
SELECT a
FROM t
EXCEPT
SELECT a
FROM t
WHERE b IS NOT NULL ;
This would use an index on (a, b)
:
SELECT a
FROM t
GROUP BY a
WHERE MIN(b) IS NOT NULL ;
Upvotes: 2
Reputation: 201
This should do it:
SELECT DISTINCT a
FROM t
WHERE b IS NULL
AND a NOT IN (SELECT a FROM t WHERE b IS NOT NULL);
Upvotes: 0
Reputation: 3405
To turn your question on it's head, you want the values from column a
where there are no non-null values for that value in column b
.
select distinct a
from table1 as t1
where 0 = (select count(*)
from table1 as t2
where t1.a = t2.a
and b is not null)
Sample fiddle is here: http://sqlfiddle.com/#!6/5d1b8/1
Upvotes: 0
Reputation: 1269773
If I understand correctly, you can do this with group by
and having
:
select a
from t
group by a
having count(b) = 0;
When you use count()
with a column name, it counts the number of non-NULL values. Hence, if all values are NULL
, then the value will be zero.
Upvotes: 6
Reputation: 67311
Try it like this:
DECLARE @tbl TABLE(a INT, b INT);
INSERT INTO @tbl VALUES(1,5),(1,NULL),(2,NULL),(2,NULL),(3,NULL);
--Your test data
SELECT * FROM @tbl;
--And this is what you want - hopefully...
SELECT DISTINCT tbl.a
FROM @tbl AS tbl
WHERE NOT EXISTS(SELECT * FROM @tbl AS x WHERE x.a=tbl.a AND b IS NOT NULL)
Upvotes: 1
Reputation: 46323
It's fairly simple to do:
SELECT A
FROM table1
GROUP BY A
HAVING COUNT(B) = 0
Grouping by A results in all the rows where the value of A is identical to be transferred into a single row in the output. Adding the HAVING
clause enables to filter those grouped rows with an aggregate function. COUNT
doesn't count NULL
values, so when it's 0, there are no other values in B.
Upvotes: 2