如何计算SQL中的非空/非空值

时间:2012-08-23 21:31:44

标签: sql sql-server sql-server-2000

我有以下数据:

Data http://i46.tinypic.com/23t5m2u.png

我想要的是计算PONo,PartNo和TrinityID字段中的值,并输出如下数据:

Desired Output http://i50.tinypic.com/nvodw.png

如何在SQL中进行此计数?

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:1)

试试这个:

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

如果要排除所有测试字段为空或空的数据,请添加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

容易!

答案 2 :(得分:-1)

另一个

Select Job_number, Item_code, Sum([Count]) as [Count] From
(
Select Job_number,Item_Code, 1 as [Count] Where PONO is not null and PONO <> ''
Union all
Select Job_number,Item_Code, 1 Where PartNo IS not Null and PartNo <> ''
Union all
Select Job_number,Item_Code, 1 Where TrinityID is not null and TrinityID <> ''
) allthree
Group by job_number, Item_code