SQL代码,用于在重复的所有实例都为空的情况下仅统计重复项
我有一个带有重复参考号的大数据集(参考重复的次数从0到37次)。我只想在两列中所有实例都为null的情况下计算引用的数量。因此,使用下表,代码应该返回1,因为只有参考代码3具有所有空值,并且重复项应该只计算一次 如果有任何帮助,我将不胜感激 这包括两个步骤:(1)隔离所有只有null的不同值对;(2) 每一个数一次。在查询中表达这一点的一种方法是:SQL代码,用于在重复的所有实例都为空的情况下仅统计重复项,sql,sql-server,Sql,Sql Server,我有一个带有重复参考号的大数据集(参考重复的次数从0到37次)。我只想在两列中所有实例都为null的情况下计算引用的数量。因此,使用下表,代码应该返回1,因为只有参考代码3具有所有空值,并且重复项应该只计算一次 如果有任何帮助,我将不胜感激 这包括两个步骤:(1)隔离所有只有null的不同值对;(2) 每一个数一次。在查询中表达这一点的一种方法是: SELECT COUNT(*) FROM ( SELECT refnum FROM #ref GROUP BY refnum
SELECT COUNT(*) FROM
(
SELECT refnum FROM #ref
GROUP BY refnum
HAVING MIN(colA) IS NULL
AND MIN(colB) IS NULL;
) AS x;
使用聚合来获取代码:
select code
from t
group by code
having max(a) is null and max(b) is null;
如果需要计数,请使用子查询:
select count(*)
from (select code
from t
group by code
having max(a) is null and max(b) is null
) t;
使用条件聚合:
select
refcode
from referencecodes
group by refcode
having sum(case when (a is null and b is null) then 0 else 1 end) = 0
上述操作将返回a
和b
中只有null
值的代码如果需要代码数:
select count(r.refcode) from (
select
refcode
from referencecodes
group by refcode
having sum(case when (a is null and b is null) then 0 else 1 end) = 0
) r
或与存在:
select
count(distinct r.refcode)
from referencecodes r
where not exists (
select 1 from referencecodes
where (refcode = r.refcode) and (a is not null or b is not null)
)
请参阅@Larnu统计所有不同的参考代码值,其中该代码没有一行,其中a或B不为空。感谢您快速而有用的回复。我可以在第一篇文章中确认代码,在第二篇文章中确认子查询中的代码。福帕斯:我还没有试过你的代码,但我已经保存了你的代码和演示,这样我就可以再参考它:)