2016-12-26 99 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