例として、私は単純なテーブルを持っています:
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)
グループ化して合計を取得する必要がありますが、グループに null 値がある場合は、合計ではなく null を取得します。私は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
パフォーマンスが優れているクエリはどれですか? それを行うための他の解決策はありますか?