当存在null时,SQL查询返回null而不是SUM

JIe*_*mON 2 sql performance

我有一个简单的表,例如:

create table #test(x int, y int)
insert into #test values(null, 1)
insert into #test values(1, 1)
insert into #test values(1, 2)
insert into #test values(2, 2)
insert into #test values(3, 2)
Run Code Online (Sandbox Code Playgroud)

我需要通过分组获得总和,但如果组具有空值,则获取null而不是sum.我可以用两个查询来做到这一点:

1) select y, case when AVG(x)<>SUM(x)/COUNT(*) then null else SUM(x) end from #test
group by y
2) select y, CASE WHEN EXISTS(select * from #test innerTest where innerTest.y=outerTest.y and x is null) then null else sum(x) end 
from #test outerTest group by y
Run Code Online (Sandbox Code Playgroud)

哪个查询性能更好?还有其他解决方案吗?

Rom*_*kar 6

你可以检查组是否有这样的空值:

select
    y,
    case when count(x) <> count(*) then null else sum(x) end
from test
group by y
Run Code Online (Sandbox Code Playgroud)

sql fiddle demo

我99.99%肯定这个会跑得比子查询更快.