如何计算SQL中的非空/非空值
我有如下数据: 我想要的是计算PONo、PartNo和TrinityID字段中的值,并输出如下数据: 如何在SQL中进行计数?试试以下方法:如何计算SQL中的非空/非空值,sql,sql-server,sql-server-2000,Sql,Sql Server,Sql Server 2000,我有如下数据: 我想要的是计算PONo、PartNo和TrinityID字段中的值,并输出如下数据: 如何在SQL中进行计数?试试以下方法: select Job_number, Item_code, case when RTRIM(PONo) = '' or PONo is null then 0 else 1 end + case when RTRIM(PartNo) = '' or PartNo is null then 0 else 1 end + case when RT
select
Job_number, Item_code,
case when RTRIM(PONo) = '' or PONo is null then 0 else 1 end +
case when RTRIM(PartNo) = '' or PartNo is null then 0 else 1 end +
case when RTRIM(TrinityID) = '' or TrinityID is null then 0 else 1 end
as [Count]
from YourTable
select Job_Number = t.Job_Number ,
Item_Code = t.Item_Code ,
"Count" = sum( case ltrim(rtrim(coalesce( PONo , '' ))) when '' then 0 else 1 end
+ case ltrim(rtrim(coalesce( PartNo , '' ))) when '' then 0 else 1 end
+ case ltrim(rtrim(coalesce( TrinityID , '' ))) when '' then 0 else 1 end
)
from dbo.my_table t
group by t.Job_Number , t.Item_Code
如果要排除所有测试字段均为null或空的数据,请添加having
子句:
having sum( case ltrim(rtrim(coalesce( PONo , '' ))) when '' then 0 else 1 end
+ case ltrim(rtrim(coalesce( PartNo , '' ))) when '' then 0 else 1 end
+ case ltrim(rtrim(coalesce( TrinityID , '' ))) when '' then 0 else 1 end
) > 0
轻松点 @Adrian-我唯一的想法是使用isnull()以某种方式测试字段,但值也可以是空字符串。另外,如果0为null,我可以很容易地添加0,但是如果不是null,如何添加1?与上面的Adrian想法类似,但我认为他的性能可能会更好,因为函数调用更少(没有合并)?我怀疑您是否会看到性能上的任何明显差异。我只是倾向于避免使用
或。这使我的类型比其他类型的类型更多。此外,使用coalesce
,我只键入一次列名。为了提高效率,ltrim
/rtrim
调用也可能是无关的,除非您必须担心空格以外的空白:SQL在概念上用空格填充短字符串到长字符串。例如,一个由CR+LF对组成的字符串与一个由2个空格组成的字符串相比,不会等于“”。