如果为null,如何使所有内容为null

时间:2018-01-29 16:27:20

标签: sql-server tsql

如果特定组中有任何null,我希望值为null。  当我使用聚合函数,即sum时,它本身处理null,但我不想处理null,我需要null在对它进行求和时应该为null。

declare @tbl table (id int,grpid char )

insert into @tbl
values(1,'a'), (2,'b'),(null,'b')

select grpid,sum(id) as val
from @tbl
group by grpid 

必需的输出:

grpid    val 
a           1
b          null

3 个答案:

答案 0 :(得分:4)

我想这很简单......

declare @tbl table (id int,grpid char )

insert into @tbl
values(1,'a'), (2,'b'),(null,'b')


;WITH cte AS(
SELECT DISTINCT grpid
  FROM @tbl
  WHERE id IS NULL
)
select t.grpid,sum(id) as val
from @tbl t
WHERE grpid NOT IN (SELECT grpid FROM cte)
GROUP BY t.grpid
UNION
SELECT grpid, NULL
  FROM cte

答案 1 :(得分:4)

您可以尝试以下方法:

方法1:

select grpid,
       case 
        when count(*)<>count(id) then null 
        else sum(id) 
       end as val
from @tbl
group by grpid

注意: Count(*)始终返回记录数,但Count(ColumnName)始终返回 ColumnName不为空的记录数

方法2:

select grpid,
       case 
        when exists(Select top 1 * from @tbl where grpid = t.grpid and id is null) then null
        else sum(id) 
       end as val
from @tbl as t
group by grpid 

方法3:

select grpid, sum(id) as val
from @tbl as t
where grpid NOT IN (Select grpid from @tbl where id is null)
group by grpid 
union
select grpid , null as val from @tbl where id is null

答案 2 :(得分:1)

另一种方法

Num   ID  Load
1   AEC 0.2093275
2   AEC 0.5384086
3   CIZ 0.1465657
4   CIZ 0.7465657
5   CIZ 0.1465657

与现有的相似但可能更有效 declare @tbl table (id int, grpid char ); insert into @tbl values (1,'a'), (2,'b'), (null,'b'), (3, 'a'), (null, 'c'); select t1.grpid , case when t2.grpid is null then sum(t1.id) else null end as 'ssum' from @tbl t1 left join @tbl t2 on t2.grpid = t1.grpid and t2.id is null group by t1.grpid, t2.grpid order by t1.grpid; 将执行不同的

UNION