你在找什么是一个完整的外连接。这将是两个步骤: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'中找到记录? –