简体   繁体   中英

SQL select column with same key if all values are null

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)

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

It looks like your logic is backwards:

  • Your query finds values in column A where there is a NULL value in column B.
  • I think you want the values in column A where there isn't a non-NULL value in column B.

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)

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM