2016-03-05 55 views
0

下面的查詢幾乎適用於所有方面,但它會返回遇到的總計數(pe.enc_id)。我試圖找到2016年的總訪問次數。通過SQL查詢查找日期範圍內的訪問次數

select distinct p.person_nbr, p.last_name, p.first_name, p.race, count(pe.enc_id) as count_of_encounters 
from patient_encounter pe 
    inner join person p on pe.person_id = p.person_id 
    inner join patient_diagnosis pd on pd.enc_id = pe.enc_id 
WHERE (p.date_of_birth between '19420101' and '19981231' and pe.enc_timestamp >= '20160101' AND pe.enc_timestamp < '20170101') 
    and pd.person_id in (select distinct p.person_id from person p inner join patient_diagnosis pd on p.person_id = pd.person_id 
where (pd.diagnosis_code_id like '250%' or pd.diagnosis_code_id like '648.0%' 
    or pd.diagnosis_code_id like '357.2' or pd.diagnosis_code_id like '362.0[0-7]' or pd.diagnosis_code_id like '366.41' or pd.diagnosis_code_id like 'E1[0-3].%' 
    or pd.diagnosis_code_id like 'O24.[0-4]0%' or pd.diagnosis_code_id like 'O24.[4-9][2-9]')) 
group by p.person_nbr, p.last_name, p.first_name, p.race 
having count(pe.enc_id) >= 2 

回答

2

您的查詢確定看起來像是過濾日期。我有一些建議:

  • 你沒有必要select distinct
  • 你的查詢是過於複雜。
  • 事實上,我不認爲這是必要的。

您似乎在尋找具有特定診斷的患者,然後計算診斷的次數。你可以做到這一切外聚集,通過擴展having條款:

所以:

select p.person_nbr, p.last_name, p.first_name, p.race, 
     count(pe.enc_id) as count_of_encounters 
from patient_encounter pe inner join 
    person p 
    on pe.person_id = p.person_id inner join 
    patient_diagnosis pd 
    on pd.enc_id = pe.enc_id 
where p.date_of_birth between '19420101' and '19981231' and 
     pe.enc_timestamp >= '20160101' AND pe.enc_timestamp < '20170101') 
group by p.person_nbr, p.last_name, p.first_name, p.race 
having count(pe.enc_id) >= 2 and 
     sum(case when pd.diagnosis_code_id like '250%' or pd.diagnosis_code_id like '648.0%' 
    or pd.diagnosis_code_id like '357.2' or pd.diagnosis_code_id like '362.0[0-7]' or pd.diagnosis_code_id like '366.41' or pd.diagnosis_code_id like 'E1[0-3].%' 
    or pd.diagnosis_code_id like 'O24.[0-4]0%' or pd.diagnosis_code_id like 'O24.[4-9][2-9]' then 1 else 0 end) > 0;