请帮助破解sql查询,以使用自连接或任何其他方式获取记录

请帮助破解sql查询,以使用自连接或任何其他方式获取记录,sql,Sql,我有一个Cust表,它有两列custid和flag。对于同一个custid,有一些记录带有标志u和I。 我只想获取只标记为U而不是I的记录。 例如: 客户表: custid flag 123 U 123 I 124 U 124 I 125 U 126 U 126 I 127 U 127 U 我想选择Custid125和127,因为他们没有国旗I 请建议查询。如果您围绕您的custid分组,则只能选择不存

我有一个Cust表,它有两列custid和flag。对于同一个custid,有一些记录带有标志u和I。 我只想获取只标记为U而不是I的记录。 例如:

客户表:

custid  flag
123      U
123      I
124      U
124      I
125      U
126      U
126      I
127      U
127      U
我想选择Custid125和127,因为他们没有国旗I


请建议查询。

如果您围绕您的
custid
分组,则只能选择不存在
标志='I'
的查询

select custid
from cust
group by custid
having count(case when flag = 'I' 
                  then 1 
                  else 0
             end) = 0
这是另一种方法。(

将具有
标志的客户编号
作为
'I'
,如果
等于0
,则选择该
客户ID

select a.num, a.custid
from
(select count(flag) as num, custid
from cust
group by custid) as a
inner join 
(select count(flag) as num, custid
    from cust
    where flag = 'U'
    group by custid) as b
on a.custid = b.custid
and a.num = b.num
结果是:

select x.custId 
from cust x
      left join (select custId from cust where flag = 'I') y
      on x.custId = y.custId
where y.custId is null 
group by x.custId
select distinct custid from cust
MINUS
select distinct custid from cust where flag = 'I'
select distinct c.custid from cust c where (select count(*) 
from cust where custid = c.custid and flag = 'I') = 0
select a.num, a.custid
from
(select count(flag) as num, custid
from cust
group by custid) as a
inner join 
(select count(flag) as num, custid
    from cust
    where flag = 'U'
    group by custid) as b
on a.custid = b.custid
and a.num = b.num