0

不幸的是,我没有权限在这些表上设置索引。

前两个WITH's导致此查询运行数小时:

;with OneAccession as (
select client_id,COUNT(patient_id) PatientCount from
(
select client_id,patient_id
from F_ACCESSION_DAILY
group by CLIENT_ID,PATIENT_ID
having COUNT(ACCESSION_ID)=1
) a
group by CLIENT_ID
)
,

TwoAccessions as (
select client_id,COUNT(patient_id) PatientCount from
(
select client_id,patient_id
from F_ACCESSION_DAILY
group by CLIENT_ID,PATIENT_ID
having COUNT(ACCESSION_ID)=2
) a
group by client_id
)



select
f.client_id
, 12*(year(getdate())-year(min(f.received_date))) + MONTH(GETDATE())-MONTH(min(f.received_date))
, COUNT(distinct f.patient_id) TotalPatients
, COUNT(f.ACCESSION_ID) TotalSpecimens
, o.PatientCount  TotalPatientsWOneSpec
, t.PatientCount TotalPatientsWTwoSpec
from F_ACCESSION_DAILY f
join
OneAccession o
on o.CLIENT_ID=f.CLIENT_ID
join
TwoAccessions t
on t.client_id=f.CLIENT_ID
where f.CLIENT_ID not in (select clientid from SalesDWH..TestPractices)
and f.SPECIMEN_SOURCE in ('Oral Fluid','Urine')
group by f.CLIENT_ID,o.PatientCount,t.PatientCount

如果我删除OneAccessionand TwoAccessions,我可以在几分钟内得到结果!

我将非常感谢有关改进我的查询语法以加快速度的任何指导!

非常感谢。

4

2 回答 2

4

如果你只做两个分组,你可以避免所有的连接。首先计算每个客户的样本,患者然后结合每个客户的计数:

WITH SpecimenCountPerPatient AS(
  SELECT client_id, patient_id, COUNT(1) SpecimenCount, MIN(received_date) FirstSpecimenDate
  FROM dbo.F_ACCESSION_DAILY
  GROUP BY client_id, patient_id
)
SELECT client_id,
       DATEDIFF(Month,MIN(FirstSpecimenDate),GETDATE()) FirstSpecimenAgeInMonthForClient,
       COUNT(1) TotalPatients,
       SUM(SpecimenCount) TotalSpecimens,
       SUM(CASE WHEN SpecimenCount = 1 THEN 1 ELSE 0 END) TotalPatientsWOneSpec,
       SUM(CASE WHEN SpecimenCount = 2 THEN 1 ELSE 0 END) TotalPatientsWTwoSpec
FROM SpecimenCountPerPatient
GROUP BY client_id;

这是一个 SQLFiddle,可以看到它的实际效果:http ://sqlfiddle.com/#!3/72e40/2

现在,我知道您说过您不能添加索引,但是在 client_id ASC、patient_id ASC INCLUDE(received_date) 上的索引会加快速度。

于 2012-10-16T13:00:39.413 回答
2

试试这个,让我知道它是否能提高性能

SELECT client_id,patient_id ,Accession_Id_Count = COUNT(ACCESSION_ID)
INTO #temp
from F_ACCESSION_DAILY 
group by CLIENT_ID,PATIENT_ID 

select 
f.client_id 
, 12*(year(getdate())-year(min(f.received_date))) + MONTH(GETDATE())-MONTH(min(f.received_date)) 
, COUNT(distinct f.patient_id) TotalPatients 
, COUNT(f.ACCESSION_ID) TotalSpecimens 
, o.PatientCount  TotalPatientsWOneSpec 
, t.PatientCount TotalPatientsWTwoSpec 
from F_ACCESSION_DAILY f 
join (select client_id,COUNT(patient_id) PatientCount from #temp where Accession_Id_Count = 1 group by CLIENT_ID ) o  on o.CLIENT_ID=f.CLIENT_ID 
join (select client_id,COUNT(patient_id) PatientCount from #temp where Accession_Id_Count = 2 group by CLIENT_ID ) t  on t.client_id=f.CLIENT_ID 
where f.CLIENT_ID not in (select clientid from SalesDWH..TestPractices) 
and f.SPECIMEN_SOURCE in ('Oral Fluid','Urine') 
group by f.CLIENT_ID,o.PatientCount,t.PatientCount 

drop table #temp
于 2012-10-16T03:28:17.867 回答