我正在尝试获取有关指定点胶日期的最新点胶日期的结果。为什么我的查询不起作用?
select
visits.patient_visit_id,pv.patient_id,pv.dispensing_date as dispensing_date,pv.dose,pv.quantity,pv.duration as days,dc.drug,r.regimen_code
FROM v_patient_visits pv
left join drugcode dc on drug_id = dc.id
left join regimen r on r.id = pv.current_regimen
left join patient_status ps on ps.id = pv.current_status
inner join
(SELECT patient_visit_id, max(dispensing_date) as max_dispensing_date
FROM `v_patient_visits`
GROUP BY patient_id
) as visits
ON visits.patient_visit_id = pv.patient_visit_id AND
visits.max_dispensing_date = pv.dispensing_date
where
pv.dispensing_date <= '2018-12-31'
and regimen_service_type = 'service one'
and ps.Name = 'Status one'
结果选择了正确的Patient_id,剂量,数量和天数,但分配日期不是最新的,参考<='2018-12-31'
v_patient_visits表如下:
patient_visit_id patient_id dispensing_date dose quantity days drug current_regimen current_status regimen_service_type
48240 000001 2019-01-16 1OD 39 39 1 11 21 service one
48240 000001 2018-12-06 1OD 39 39 1 11 21 service one
48240 000001 2017-12-05 1OD 39 39 2 12 21 service one
48240 000001 2016-12-04 1OD 39 39 3 13 21 service one
48241 000002 2019-01-10 1BD 40 40 4 14 22 service two
48241 000002 2018-11-10 1BD 40 40 4 14 22 service two
48241 000002 2017-11-09 1BD 40 40 5 15 22 service two
48241 000002 2016-11-08 1BD 40 40 6 16 22 service two
48242 000003 2017-10-15 1OD 41 41 7 17 21 service one
48242 000003 2016-10-14 1OD 41 41 8 18 21 service one
48242 000003 2015-10-13 1OD 41 41 9 19 21 service one
同一个Patient_id可能有多个条目,我希望它选择最近的配药日期
药物代码表如下:
id drug
1 Drug one
2 Drug two
3 Drug three
4 Drug four
方案表如下:
id regimen_code
11 Regimen one
12 Regimen two
13 Regimen three
14 Regimen four
Patient_status表如下:
id Name
21 Status one
22 Status two
23 Status three
24 Status four
我希望输出如何:
patient_visit_id patient_id dispensing_date dose quantity days drug regimen_code
48240 000001 2018-12-06 1OD 39 39 Drug one Regimen one
48242 000003 2017-10-15 1OD 41 41 Drug seven Regimen seven
答案 0 :(得分:2)
关闭。您需要在该日期加入子查询!
(SELECT patient_id, max(dispensing_date) as max_dispensing_date
FROM `v_patient_visits`
GROUP BY patient_id
) visits
ON visits.patient_visit_id = pv.patient_visit_id AND
visits.max_dispensing_date = pv.dispensing_date