我有一个简单的表格,例如:
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)
我需要通过分组得到总和,但如果组有一个空值,那么得到空值而不是总和。我可以通过两个查询来做到这一点:
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
哪个查询的性能更好?还有其他解决方案吗?