2016-12-26 55 views
-1

我有3个表格参与项目,patient_services和患者。 此查询MySQL查询计算唯一ID,计数记录数和组数(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 

所以禄有双打,我可以在PHP循环 计算SER但由于交战相同的id和patient_services表计的患者不是唯一的。

如何根据位置选择按服务数量和独特患者进行分组,两个表中(不是每个都像现在这样)?

谢谢。

+0

欢迎您。但问题是什么? – Shadow

+0

@Shadow 如何根据位置将选择按服务数量和独特患者分组在两张表格中(不是每个人都喜欢它)? – user3315525

+0

'ur'('ps_ur','eng_ur')是一个患者ID? “ser”这个词的意思是“多少条记录”?并且您希望每个loc的一个结果行使用'ser'总数和不同的患者数,因为您不在乎您是否在'patient_services'或'engagementments'中找到记录? –

回答

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; 
+0

谢谢!这是伟大的 – user3315525

+0

“选择 l.loc, 总和(合并(ps.cnt,0)+ COALESCE(e.cnt,0))AS SER, 计数(不同l.patient)从 患者 ( 选择ps_user_loc如LOC,ps_ur从patient_services患者 工会 选择eng_user_loc如LOC,eng_ur从其中长度(eng_ur)> 0 )升 左外连接 ( 接合患者...” – user3315525