我想从SQL Server表中选择特定值

时间:2011-10-12 14:01:51

标签: sql-server

我想从名为Prescriptions的表中选择特定值。我想选择在一段时间内使用以下药物的患者:

这是我一直在使用的选择,但它返回仅使用一种或两种药物的患者。我希望能够带来正在使用这两种药物的患者:

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

有人可以帮忙吗?非常感谢你!

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 %'
        )

答案 2 :(得分:0)

你必须为你的医生创建一个表,然后在其上获得处方。