[英]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. 我有两列ColumnA和ColumnB,有时columnB不会被填充,所以应该e。 I'm looking for a query that will only select if all ColumnA is unpopulated.
我正在寻找仅在所有ColumnA未填充的情况下才会选择的查询。
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. 这就是我的意思,但这是不正确的,因为它说ColumnA为null且具有相同的值,并且已填充ColumnB。 I want the query only to return rows if all of columnB is unpopulated.
如果所有columnB都未填充,我只希望查询返回行。
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: 您要消除的是具有
ColumnB
值的那些:
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 因为
COUNT(Expression)
仅计算非空表达式值
It looks like your logic is backwards: 看来您的逻辑倒退了:
Try adding NOT
in two places and add DISTINCT
to avoid getting duplicate results: 尝试在两个位置添加
NOT
并添加DISTINCT
以避免重复的结果:
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: 另外,如果
ColumnA
可以为NULL,则必须从内部查询中排除这些NULL值,否则NOT IN
表达式将返回NULL
而不是True
,因此将不返回任何结果:
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. 使用EXCEPT。 This can be expressed as
这可以表示为
Get Column A, EXCEPT where some non-null in Column B for that column A
获取A列,但该列A的B列中的一些非空值除外
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? 有关EXCEPT的更多信息: 为什么T-SQL中存在EXCEPT?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.