子查询中的in和not in

时间:2019-02-07 20:23:15

标签: sql oracle-sqldeveloper

我试图提取具有代码“ H”但不同时具有“ H”和“ J”的记录,例如:

ID      NBR TYPE_CODE
34134   123 H
34134   123 J
35555   231 H
35555   233 H
42012   421 H
42012   421 J

我只想提取这些记录,因为它们没有对应的带有'J'的记录:

ID    NBR
35555 231
35555 233 

对于我运行的查询,我得到了上述所有ID和NBR,因为它们确实具有“ H”代码。我该如何获取仅具有“ H”代码而不同时具有两者的代码?

4 个答案:

答案 0 :(得分:2)

使用not exists

select t.ID, t.NBR from tablename t
where t.TYPE_CODE = 'H'
and not exists (
  select 1 from tablename where ID = t.ID AND TYPE_CODE = 'J'
)

答案 1 :(得分:0)

使用“不在”

Create Table #tbl
(
id Int,
nbr Int,
type_code Char(1)
)
Insert Into #tbl Values
(34134,123,'H'),    
(34134,123,'J'),
(35555,231,'H'), 
(35555,233,'H'),
(42012,421,'H'),
(42012,421,'J')

查询

Select * From #tbl Where id Not In 
(Select Distinct id From #tbl Where type_code = 'J')

结果

id      nbr type_code
35555   231 H
35555   233 H

答案 2 :(得分:0)

您写道您需要:

  

具有代码“ H”但不同时具有“ H”和“ J”的记录

SELECT ID, NBR FROM [your_table] T
    WHERE 
        EXISTS(SELECT * FROM [you_table] T2 
            WHERE 
                T1.ID = T2.ID AND T1.NBR=T2.ID 
                AND T2.TYPE_CODE = 'H')
        AND NOT EXISTS(
            SELECT * FROM [you_table] T2 
                WHERE 
                   T1.ID = T2.ID AND T1.NBR=T2.ID 
                   AND T2.TYPE_CODE = 'J')
        )

这必须是您的查询

答案 3 :(得分:0)

使用join

select t1.id, t1.nbr 
from table1 t1 inner join 
(
    select t.id 
    from table1 t 
    group by t.id 
    having max(t.type_code) = min(t.type_code)
) t2 on t1.id = t2.id
where t1.type_code = 'H'

table1更改为表格名称。