仅在访问一个位置时需要选择

时间:2016-07-06 14:30:22

标签: sql sql-server

在下面的SQL中,它只查看来自location_ID = 5的那些优惠券。我如何编码,我只想要一个只访问location_ID 5的Patient_ID?

SELECT "Vouchers"."Patient_ID", "vwGenPatInfo"."Patient_Number",  
       "Practitioners"."Practitioner_ID", "Practitioners"."First_Name",   
       "Practitioners"."Last_Name", "vwGenPatInfo"."Patient_First_Name", 
       "vwGenPatInfo"."Patient_Last_Name", "vwGenPatInfo"."Patient_DOB", 
       "vwGenPatInfo"."Patient_Sex", "Vouchers"."Carrier_ID", 
       "Vouchers"."Billing_Date", "Vouchers"."Patient_Policy_ID", 
       "Vouchers"."Location_ID"
FROM   ("Ntier_70751"."PM"."vwGenPatInfo" "vwGenPatInfo" 
INNER JOIN "Ntier_70751"."PM"."Vouchers" "Vouchers" 
ON "vwGenPatInfo"."Account_ID"="Vouchers"."Account_ID") 
INNER JOIN "Ntier_70751"."PM"."Practitioners" "Practitioners" 
ON "Vouchers"."Actual_Prov_Practitioner_ID"="Practitioners"."Practitioner_ID"
-- 
WHERE  "Vouchers"."Location_ID"=5

4 个答案:

答案 0 :(得分:2)

这是一种方法。我也摆脱了所有那些不需要的双引号并使用了适当的别名。

SELECT V.Patient_ID
    , gpi.Patient_Number
    , P.Practitioner_ID
    , P.First_Name
    , P.Last_Name
    , gpi.Patient_First_Name
    , gpi.Patient_Last_Name
    , gpi.Patient_DOB
    , gpi.Patient_Sex
    , V.Carrier_ID
    , V.Billing_Date
    , V.Patient_Policy_ID
    , V.Location_ID
FROM Ntier_70751.PM.vwGenPatInfo gpi 
INNER JOIN Ntier_70751.PM.Vouchers V ON gpi.Account_ID = V.Account_ID 
INNER JOIN Ntier_70751.PM.Practitioners P ON V.Actual_Prov_Practitioner_ID = P.Practitioner_ID
cross apply
(
    select V2.Account_ID
    from Ntier_70751.PM.Vouchers V2
    where V2.Account_ID = V.Account_ID

    group by V2.Account_ID
    HAVING MAX(Location_ID) = 5
        AND MIN(Location_ID) = 5
) x

答案 1 :(得分:0)

说出一个条件;

WHERE "Vouchers"."Location_ID" = 5

答案 2 :(得分:0)

我会不存在

SELECT "Vouchers"."Patient_ID", "vwGenPatInfo"."Patient_Number",  
       "Practitioners"."Practitioner_ID", "Practitioners"."First_Name",   "Practitioners"."Last_Name", "vwGenPatInfo"."Patient_First_Name", "vwGenPatInfo"."Patient_Last_Name", "vwGenPatInfo"."Patient_DOB", "vwGenPatInfo"."Patient_Sex", "Vouchers"."Carrier_ID", "Vouchers"."Billing_Date", "Vouchers"."Patient_Policy_ID", "Vouchers"."Location_ID"
FROM "Ntier_70751"."PM"."vwGenPatInfo" "vwGenPatInfo" INNER JOIN 
     "Ntier_70751"."PM"."Vouchers" "Vouchers"
     ON "vwGenPatInfo"."Account_ID" = "Vouchers"."Account_ID" INNER JOIN
        "Ntier_70751"."PM"."Practitioners" "Practitioners"
     ON "Vouchers"."Actual_Prov_Practitioner_ID" = "Practitioners"."Practitioner_ID"
 WHERE  "Vouchers"."Location_ID"=5
   and not exists (select 1 
                    FROM "Ntier_70751"."PM"."Vouchers" "Vouchers2"
                     WHERE "Vouchers2"."Patient_ID" = "Vouchers2"."Patient_ID" 
                       AND "Vouchers2"."Location_ID"<>5)

答案 3 :(得分:0)

只使用条件'WHERE'优惠券“。”Location_ID“= 5'将返回访问该位置的所有Patient_ID,至少一次但不是唯一的。有几种方法可以做到,但最干净的是使用max(location_id)&lt; 5和min(location_id)&gt; 5