你在找什麼是一個完整的外連接。這將是兩個步驟:1.從表中獲取loc/patient對並加入,2.通過loc進行聚合。在標準SQL中:
select
loc,
sum(coalesce(ps.cnt, 0) + coalesce(e.cnt, 0)),
count(distinct patient)
from
(
select
ps_user_loc as loc,
ps_ur as patient,
count(*) as cnt
from patient_services
group by ps_user_loc, ps_ur
) ps
full outer join
(
select
eng_user_loc as loc,
eng_ur as patient
count(*) as cnt,
from engagements
where length(eng_ur) > 0
group by eng_user_loc, eng_ur
) e using (loc, patient)
group by loc;
不幸的是,MySQL不支持完整的外連接(並且不使用using子句)。一種方法是首先獲得所有位置/患者,然後加入:
select
l.loc,
sum(coalesce(ps.cnt, 0) + coalesce(e.cnt, 0)),
count(distinct l.patient)
from
(
select ps_user_loc as loc, ps_ur as patient from patient_services
union
select eng_user_loc as loc, eng_ur as patient from engagements
) l
left outer join
(
select
ps_user_loc as loc,
ps_ur as patient,
count(*) as cnt
from patient_services
group by ps_user_loc, ps_ur
) ps on ps.loc = l.loc and ps.patient = l.patient
left outer join
(
select
eng_user_loc as loc,
eng_ur as patient,
count(*) as cnt
from engagements
where length(eng_ur) > 0
group by eng_user_loc, eng_ur
) e on e.loc = l.loc and e.patient = l.patient
group by l.loc;
歡迎您。但問題是什麼? – Shadow
@Shadow 如何根據位置將選擇按服務數量和獨特患者分組在兩張表格中(不是每個人都喜歡它)? – user3315525
'ur'('ps_ur','eng_ur')是一個患者ID? 「ser」這個詞的意思是「多少條記錄」?並且您希望每個loc的一個結果行使用'ser'總數和不同的患者數,因爲您不在乎您是否在'patient_services'或'engagementments'中找到記錄? –