4

我有如下数据:

数据

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

期望的输出

如何在 SQL 中进行此计数?

4

2 回答 2

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
于 2012-08-23T21:37:39.980 回答
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

简单的!

于 2012-08-23T21:46:06.977 回答