1

我的where exists条款不起作用。我错过了什么微不足道的事情?

select * from patient as p
where exists
(
    select p.patientid, count(*) from tblclaims as c 
    inner join patient as p on p.patientid=c.patientid
    and p.admissiondate = c.admissiondate
    and p.dischargedate = c.dischargedate
    group by p.patientid
    having count(*)>500
)

如您在查询中看到的那样,患者和 tblclaims 通过三字段复合键连接在一起。

4

3 回答 3

2

count(*) from tblclaims as c是不必要的,可能会抛出查询。

此外,您没有WHERE加入patient p您的条款的exists条款。

更不用说您p在主查询和子句中都用作别名exists,这只是令人困惑。

你可能想要这样的东西:

select * from patient
where exists
(
    select p.patientid 
    from tblclaims as c 
    inner join patient as p on p.patientid=c.patientid
        and p.admissiondate = c.admissiondate
        and p.dischargedate = c.dischargedate
    where patient.patientid = p.patientid
    group by p.patientid
    having count(*)>500
)
于 2012-07-24T02:00:02.110 回答
1

您根本不需要在子查询中使用内连接;这实际上是你额外结果的原因。您应该在外部查询中引用“p”。

select * from patient as p
where exists
(
    select 1 from tblclaims as c 
    where p.patientid = c.patientid
       and p.admissiondate = c.admissiondate
       and p.dischargedate = c.dischargedate
    group by c.patientid
    having count(*)>500
)
于 2012-07-24T02:08:19.437 回答
0

我不太喜欢存在。也许您可以使用其他功能。尝试这个:

select * from patient as p
where patientid IN
(
    select p.patientid from tblclaims as c 
    inner join patient as p on p.patientid=c.patientid
    and p.admissiondate = c.admissiondate
    and p.dischargedate = c.dischargedate
    group by p.patientid
    having count(*)>500
)
于 2012-07-24T02:02:20.537 回答