2009-07-19 218 views
0

任何幫助,非常感謝。空查詢返回

我有一個表,醫院:

Nurse + Year + No.Patients
A001 |2000 | 23
A001 |2001 | 30
A001 |2002 | 35

B001 |2000 | 12
B001 |2001 | 15
B001 |2002 | 45

C001 |2000 | 50
C002 |2001 | 59
C003 |2002 | 69
etc

What I am trying to do is work out which nurse had the greatest increase of patients for the years 2000 - 2002.

Clearly B001 did as her patients increased from 12 to 45 and increase of 33 and what I am trying to produce is the result B001 | 33

這是我到目前爲止有:

select a.nurse,a.nopats from hospital as a 
    join 
    (select nurse,max(nopats)-min(nopats) as growth 
     from hospital where year between 2000 and 2002 group by nurse) as s1 
    on a.nurse = s1.nurse and a.nopats = s1.growth 
    where year between 2000 and 2002; 

,但我得到的返回是一個空集。

我想我需要加入後的整體max(nopats)

在這裏的任何幫助將是偉大的。

謝謝!

回答

1

試試這個:

SELECT nurse, (max(nopats) - min(nopats)) AS growth 
    FROM hospital 
WHERE year BETWEEN 2000 AND 2002 
GROUP BY nurse 
ORDER BY growth DESC 
LIMIT 1; 

結果:B001 | 33由於限制1;如果您想獲得更多結果,請將其丟棄。

+0

哈哈,幾乎和我的一模一樣! :) – Christian 2009-07-19 00:44:44

+0

嘿嘿,是的,我們幾乎在同一時間發佈它,很好的工作! – capfu 2009-07-19 18:04:24

1
SELECT nurse, MAX(nopats) - MIN(nopats) AS Growth 
    FROM hospital 
WHERE year BETWEEN 2000 AND 2002 
GROUP BY nurse 
ORDER BY Growth 

這應該做到這一點。讓我知道,如果那就是你需要的。