I have simple table, by example:
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)
I need to get the sum with grouping, but if the group has a null value, then get null instead of sum. I can do it with two query:
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
Which query is better in performance? And are there other solutions to do it?