我很高兴这次至少有一个工作实例的问题。这曾经是一个有效的查询,当我有一个标准,如果它有一个计数> = 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
答案 0 :(得分: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
答案 1 :(得分:1)
您的第一个IN
只是检查是否存在,因此无需使用HAVING
(另一方面,为什么要将COUNT(1)
与字符串进行比较?是INT
,因此您应该使用>=1
或>=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