SQL查询以查找不包含请求的代码类型的行

时间:2018-10-22 12:11:52

标签: sql tsql

我有一个包含ind_ref和code_type的表。 我只想查找那些没有code_type = 3299的ind_ref。下面是示例表。

IND_REF CODE TYPE
   84815    9573
   84815    9415
   84816    3299<----don't want this IND_REF
   84816    9415
   84817    3299<----don't want this IND_REF
   84817    9573
   84818    9577
   84818    9573

我希望输出仅包含IND_REF

Ind_ref
 84815
 84818

任何寻求帮助的人。

4 个答案:

答案 0 :(得分:1)

您可以按ind_ref对数据进行分组,并且只接受没有代码3299的数据

select ind_ref
from your_table
group by ind_ref
having sum(case when code_type = 3299 then 1 else 0 end) = 0

答案 1 :(得分:1)

我将使用group byhaving

select ind_ref
from t
group by ind_ref
having sum(case when type = 3299 then 1 else 0 end) = 0;

这会ind_ref返回一行,这似乎是您想要的。

答案 2 :(得分:0)

您可以使用not exists

select distinct t.IND_REF
from table t
where not exists (select 1 
                  from table t1 
                  where t1.IND_REF = t.IND_REF and t1.CODETYPE = 3299
                 );

这里是Demo

答案 3 :(得分:0)

使用not in

    with your_table (IND_REF, codetype) as (

   SELECT 84815  ,  9573UNION ALL
   SELECT 84815  ,  9415UNION ALL
   SELECT 84816  ,  3299UNION ALL
   SELECT 84816  ,  9415UNION ALL
   SELECT 84817  ,  3299UNION ALL
   SELECT 84817  ,  9573UNION ALL
   SELECT 84818  ,  9577UNION ALL
   SELECT 84818  ,  9573
)select distinct t.IND_REF from your_table t where t.IND_REF not in
    ( select IND_REF from your_table t1 where         
       t1.codetype=3299
    )

    output
    IND_REF
    84815
    84818

不存在也很好

with your_table (IND_REF, codetype) as (

   SELECT 84815  ,  9573UNION ALL
   SELECT 84815  ,  9415UNION ALL
   SELECT 84816  ,  3299UNION ALL
   SELECT 84816  ,  9415UNION ALL
   SELECT 84817  ,  3299UNION ALL
   SELECT 84817  ,  9573UNION ALL
   SELECT 84818  ,  9577UNION ALL
   SELECT 84818  ,  9573
)

select distinct t.IND_REF
from your_table t
where not exists (select 1 
                  from your_table t1 
                  where t1.IND_REF = t.IND_REF and t1.codetype = 3299
                 );

Demo in fiddle