MySQL Query用于计算唯一ID,计数记录数和分组数(3个表)

时间:2016-12-26 21:34:18

标签: mysql sql

我有3个餐桌,患者服务和患者。 此查询

SELECT 
    ps_user_loc AS loc, COUNT(ps_id) AS ser, Count(Distinct  ps_ur) AS patient
FROM patient_services 
GROUP BY loc 

UNION ALL 

SELECT 
    eng_user_loc AS loc, COUNT(eng_id) AS ser, Count(Distinct  eng_ur) AS patient 
FROM engagements 
WHERE LENGTH( eng_ur )>0 
GROUP BY loc

返回

loc           ser   patient 
CABOOLTURE    354       255
KILCOY         15        12 
RBWH         1840       476 
RBWH           34        27 
REDCLIFFE       3         3 
TPCH           11         9

所以loc有两倍,我可以在php循环中计算ser 但是,患者数量并不是唯一的,因为在参与和patient_services表中具有相同的ID。

如何选择按位置分组的选择,包括服务数量和两个表中的独特患者(现在不是每个人都有)?

谢谢。

1 个答案:

答案 0 :(得分:0)

您正在寻找的是一个完整的外部联接。这将是两个步骤: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;