0

我在Filter類中有4個以下的屬性。我將解析4個以下屬性到StoredProcedure並獲取過濾結果。如何創建SQL運算符組合像ALL IN,NOT ALL

​​

我的存儲過程將有四個參數,如下所示。 例如:

@ * MustHaveAll *條件= 「1,2」

@ * MustNotHaveAll *條件= 「3,4」

@ * MustHaveAtLeastOne *條件=「 5,6,7,8-「

@ * MustNotHaveAtLeastOne *條件= 」9,10「

我正在使用一個UDF,它返回一個帶有Ids列的表。

我的問題:

基本上我可以使用SQL「IN」運算符查找誰擁有至少一個條件的患者(即:@MustHaveAtLeastOneCondition)和「NOT IN」運算符組合過濾@MustNotHaveAnyConditions。

是否有任何SQL運算符(或esay方式)來過濾MustHaveAllConditions,MustNotHaveAllConditions參數?

回答

1
-- Patients 
declare @Patient table (PatientID int) 

-- Conditions per patient 
declare @PatientCondition table (PatientID int, ConditionID int) 

-- Conditions table generated from param string 
declare @Condition table (ConditionID int) 

-- Test data 
insert into @Patient 
select 1 union all 
select 2 union all 
select 3 

insert into @PatientCondition 
select 1, 1 union all 
select 1, 2 union all 
select 1, 3 union all 
select 2, 1 union all 
select 3, 3 

insert into @Condition 
select 1 union all 
select 2 


-- MustHaveAll 
select * 
from @Patient as P 
where P.PatientID in 
    (
    select PC.PatientID 
    from @PatientCondition as PC 
     inner join @Condition as C 
     on PC.ConditionID = C.ConditionID 
    group by PC.PatientID 
    having count(PC.ConditionID) = (select count(ConditionID) from @Condition) 
) 

--MustNotHaveAll 
select * 
from @Patient as P 
where P.PatientID not in 
    (
    select PC.PatientID 
    from @PatientCondition as PC 
     inner join @Condition as C 
     on PC.ConditionID = C.ConditionID 
    group by PC.PatientID 
    having count(PC.ConditionID) = (select count(ConditionID) from @Condition) 
) 

-- MustHaveAtLeastOne 
select * 
from @Patient as P 
where P.PatientID in 
    (
    select PC.PatientID 
    from @PatientCondition as PC 
     left outer join @Condition as C 
     on PC.ConditionID = C.ConditionID 
    where C.ConditionID is not null 
) 

--MustNotHaveAtLeastOne 
select * 
from @Patient as P 
where P.PatientID not in 
    (
    select PC.PatientID 
    from @PatientCondition as PC 
     left outer join @Condition as C 
     on PC.ConditionID = C.ConditionID 
    where C.ConditionID is not null 
) 
+0

這很好。如果我想在一個SQL查詢中合併這四個條件以獲得患者的最終名單,您能告訴我最有效的方法嗎? – CharithJ 2011-05-16 06:08:26

+1

@CharithJ - 您可以將不同查詢中的where子句添加到一個查詢中,並用'和'分開。 (...)中的PatientID以及(...)和...中的PatientID等。 – 2011-05-16 06:17:29

0

真的不是一個簡單的方法來做你所描述的。我會做的是可能把你的字符串和分裂成一個表變量,然後使用右,左和內部聯合的組合來從我的輸出中刪除另一個表變量的結果。