0

今回は少なくとも実用的な例で質問できてうれしいです。カウント >= 1 の場合に結果が返されるという基準があったとき、これは効率的なクエリでした。次に、異なるコード値に対して、それらが 2 回以上発生した場合に追加のカウントを行う必要がありました。クエリの実行は数秒から約 43 秒になりました。

私は論理が正しいと思いますが、誰かがこれを行うためのより効率的な方法を持っているかどうか疑問に思っていました.

select person.person_id
from person
where 
person.person_id in (
        select procedure.person_id
        from procedure
        where
        procedure.performed_by = '555555'
        and procedure.code in (
                '99201', '99202'
                )
        and year(procedure.service_date) = year(getdate())
        group by procedure.person_id
        having count(1) >= '1'
        ) -- having count >= 1 occurrences
or person.person_id in (
        select person_id
        from procedure
        where
        procedure.performed_by = '55555'
        and code in (
                '99304','99305'
                )
        and year(procedure.service_date) = year(getdate())
        group by procedure.person_id
        having count(1) >= '2'
        ) -- having count >= 2 occurrences
4

2 に答える 2

1

最初INは存在を確認するだけなので、実際に使用する必要はありませんHAVING(別の注意として、なぜCOUNT(1)文字列と比較するのですか?結果は であるため、代わりにorINTを使用する必要があります)。また、比較する前に関数を使用しています。その列で可能なインデックスを使用できないため、これを行うべきではありません。私はあなたのクエリをこのように書きます:>=1>=2service_date

select p.person_id
from person p
where exists (  select 1
                from procedure
                where
                procedure.performed_by = '555555'
                and procedure.code in ('99201', '99202')
                and procedure.service_date >= dateadd(year,datediff(year,0,getdate()),0)
                and procedure.service_date < dateadd(year,datediff(year,0,getdate())+1,0)
                and procedure.person_id = p.person_id)
or person.person_id in (
        select person_id
        from procedure
        where
        procedure.performed_by = '55555'
        and code in ('99304','99305')
        and procedure.service_date >= dateadd(year,datediff(year,0,getdate()),0)
        and procedure.service_date < dateadd(year,datediff(year,0,getdate())+1,0)
        group by procedure.person_id
        having count(1) >= 2
        ) -- having count >= 2 occurrences
于 2013-08-23T15:46:02.200 に答える