Reputation:
I have two columns , ColumnA and ColumnB, occassionally columnB doesnt gets populated and it should e. I'm looking for a query that will only select if all ColumnA is unpopulated.
ColumnA|ColumnB
Apples|
Apples|
Apples|Orange
This is what i'm but this is incorrect because it says ColumnA is null with the same value and ColumnB is populated. I want the query only to return rows if all of columnB is unpopulated.
SELECT ColumnA
FROM tblMyTable
WHERE ColumnA IN
(SELECT ColumnA
FROM tblMyTableB
WHERE ColumnB IS NULL)
Upvotes: 0
Views: 1687
Reputation: 432662
Using EXCEPT. This can be expressed as
Get Column A, EXCEPT where some non-null in Column B for that column A
DECLARE @MyTable TABLE (ColumnA varchar(20) NOT NULL, ColumnB varchar(20) NULL);
INSERT @MyTable VALUES
('Apple', NULL),('Apple', NULL),('Apple', 'Orange'),
('Banana', NULL),('Banana', NULL),
('Strawberry', 'Pie'), ('Strawberry', 'Pie')
SELECT ColumnA FROM @MyTable
EXCEPT
SELECT ColumnA FROM @MyTable WHERE ColumnB IS NOT NULL
More on EXCEPT: Why does EXCEPT exist in T-SQL?
Upvotes: 0
Reputation: 239824
You current query gives you too many results. The ones you want to eliminate are those where there is a ColumnB
value:
SELECT ColumnA
FROM tblMyTable
WHERE ColumnA IN
(SELECT ColumnA
FROM tblMyTableB
WHERE ColumnB IS NULL)
AND NOT ColumnA IN
(SELECT ColumnA
FROM tblMyTableB
WHERE ColumnB IS NOT NULL)
Or, smarter is:
select ColumnA,COUNT(ColumnB) from tblMyTable
group by ColumnA having COUNT(ColumnB) = 0
Because COUNT(Expression)
only counts non-null expression values
Upvotes: 3
Reputation: 839164
It looks like your logic is backwards:
Try adding NOT
in two places and add DISTINCT
to avoid getting duplicate results:
SELECT DISTINCT ColumnA
FROM tblMyTable
WHERE ColumnA NOT IN
(SELECT ColumnA
FROM tblMyTableB
WHERE ColumnB IS NOT NULL)
In addition, if ColumnA
can be NULL then you'll have to exclude those NULL values from your inner query otherwise the NOT IN
expression will return NULL
instead of True
and so no results will be returned:
SELECT DISTINCT ColumnA
FROM tblMyTable
WHERE ColumnA NOT IN
(SELECT ColumnA
FROM tblMyTableB
WHERE ColumnA IS NOT NULL
AND ColumnB IS NOT NULL)
Upvotes: 2