2012-11-24 193 views
1

我試圖做一個查詢,但我不知道該怎麼做。AVG COUNT查詢

這些都是表:

Table Hospital   Table Doctor  Table Work 

    Hid Country   ic    Hid  ic 
    1  England   1     1  1 
    2  Spain   2     1  2 
    3  France   3     1  3 
    4  England   4     2  4 
    5  China   5     4  5 

結果,我想:

Country  Average of Doctors Working on that Hospitals of that Country 
    England  2 (the doctor with ic 1, 2, 3, and 4/number of hid) 
    Spain  1 
    France  0 
    China  0 

我想:

SELECT DISTINCT H.country, AVG(D.ic) 
FROM Hospital H, Doctor D 
WHERE H.hid IN 
     (SELECT W.hid 
     FROM Work W 
     WHERE W.ic IN 
       (SELECT COUNT(D.ic) 
       FROM D Doctor .... 
      ) 
    ) 
GROUP BY(H.country); 
+0

能否請您分享您查詢? –

+0

我在西班牙看到一名醫生,而不是在中國。 –

+0

是的,我的錯誤。 – tomss

回答

1

試試這個

select H.Country, count(W.ic)/count(distinct H.hid) as [Average] 
from Hospital as H 
    left outer join Work as W on W.Hid = H.Hid 
group by H.Country 

SQL FIDDLE

0

首先獲得醫生各醫院的號碼,然後得到的平均值是:

select country, avg(docs) as avg_doctors_working 
from (
     select country, h.hid, count(*) as docs, 
     from hospital h 
    left join work w on w.hid = h.hid 
    group by 1, 2) x 
group by 1;