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

这会加快速度吗?

WITH CTE AS
(
    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'

    UNION

    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'
)

select person.person_id
from person 
JOIN CTE ON CTE.Person_id = Person.Person_Id
于 2013-08-23T15:42:39.693 回答
1

你的第一个IN只是检查存在,所以没有真正需要使用HAVING(另一方面,你为什么要COUNT(1)与字符串比较?,结果是 an INT,所以你应该使用>=1or>=2代替)。您还在service_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 回答