3

例として、私は単純なテーブルを持っています:

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

パフォーマンスが優れているクエリはどれですか? それを行うための他の解決策はありますか?

4

2 に答える 2

7

次のように、グループに null があるかどうかを確認できます。

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

sql fiddle demo

これは、サブクエリを使用した場合よりも高速に実行されると 99.99% 確信しています。

于 2013-10-24T19:15:53.263 に答える