2016-12-27 73 views
3

我有一張表,其中包含醫療數字和過程的列。有很多行和醫療號碼可以重複許多程序;例如:如何從一個表中選擇條件跨同一列的多行

Mid_no procedure 
-------------------- 
100.   20 
100.   30 
200.   30 

我想選擇具有程序30和不具有程序20在上述例子中所有mid_no,所期望的結果將是:

Mid_no. Procedure 
--------------------- 
200.  30 

回答

3
SELECT t.mid_no, 
    t.procedure 
FROM TABLE t 
WHERE NOT EXISTS 
    (SELECT 1 FROM TABLE t1 WHERE t1.mid_no = t.mid_no AND t1.procedure = 20 
) 
AND t.procedure = 30; 
+0

對不起,我不明白T是我的桌子什麼是T1? –

+0

@ahmeddevil它是桌子的別名。這非常有用,因此我們不必編寫完整的表名來限定列。 – GurV

+0

@ahmed在上述查詢中使用您自己的表名代替** TABLE ** – GurV

1
select mid_no from table where procedure = 30 
intersect 
select mid_no from table where procedure != 20 
0

只需掃描一張桌子,即可使用:

select distinct Mid_no 
from (
     select count(case when procedure=20 then 1 end) over (partition by Mid_no) as has20, 
       count(case when procedure=30 then 1 end) over (partition by Mid_no) as has30, 
       Mid_no 
     from yourTable 
    ) 
where has20 = 0 
    and has30 != 0 

內部查詢以兩個不同的值計算2030的出現次數,對於每個Mid_no;外部人只挑選沒有發生的唯一記錄20和至少一個發生的30

相關問題