2011-10-12 60 views
1

我想從名爲Prescriptions的表中選擇特定值。我想選擇在一定時間段內使用以下藥物的患者:我想從SQL Server表中選擇特定值

這是我一直在使用的選擇,但它返回僅使用一種或兩種藥物的患者。我希望能夠爲患者提供兩種藥物:

SELECT MEDICINE, CLIENTNUMBER 
FROM PRESCRIPTIONS 
where 
(MEDICINE like 'simvastatin %' OR 
MEDICINE like 'amlodipine%') 
AND 
DATE between '11/23/2010' and '11/23/2010' 
Group by CLIENTNUMBER, MEDICINE 
Order by CLIENTNUMBER 

任何人都可以幫忙嗎?非常感謝你!

回答

1

試試這個:

SELECT p1.Medicine m1, p2.Medicine m2, p1.ClientNumber cn 
FROM Prescriptions p1 INNER JOIN Prescriptions p2 
ON p1.ClientNumber = p2.ClientNumber 
WHERE (
    ((m1 LIKE 'simvastatin %') AND (m2 LIKE 'amlodipine%')) OR 
    ((m2 LIKE 'simvastatin %') AND (m1 LIKE 'amlodipine%')) 
    AND Date BETWEEN '11/23/2010' AND '11/23/2010') 
GROUP BY cn, m1 
ORDER BY cn 
+0

看起來這是一排回來的兩種藥物。應該是一個小的修復,但。 – Andomar

1

您就可以使用兩個exists條款,以確保客戶端有兩種藥品訂閱:

select p.MEDICINE 
,  p.CLIENTNUMBER 
from PRESCRIPTIONS as p 
where p.DATE between '11/23/2010' and '11/23/2011' 
     and exists 
     (
     select * 
     from PRESCRIPTIONS as p2 
     where p2.DATE between '11/23/2010' and '11/23/2011' 
       and p2.CLIENTNUMBER = p.CLIENTNUMBER 
       and p2.MEDICINE like 'simvastatin %' 
     ) 
     and exists 
     (
     select * 
     from PRESCRIPTIONS as p3 
     where p3.DATE between '11/23/2010' and '11/23/2011' 
       and p3.CLIENTNUMBER = p.CLIENTNUMBER 
       and p3.MEDICINE like 'amlodipine %' 
     ) 
+0

謝謝!它的工作,但也爲那段時間的病人返回其他藥物,我怎麼能過濾它,所以它只會返回我想要的那些產品? – user734781

0

,你必須爲你的medician的然後讓分裂創建一個表處方就可以了。

相關問題