语句在哪里取消结果?

时间:2019-03-13 20:48:07

标签: sql oracle

我想从以下示例中找到UID个数字,这些数字遇到了矛盾的where陈述,但它是正确的。这个想法是要证明如果数据中有“父”和“闭”,则“打开”和“子”将不存在。以下示例应返回UID=789作为用例错误。

UID     Title   Business
123     Parent  Open
123     Child 1 Open
123     Child 2 Open
456     Parent  Closed
456     Child 1 Closed
456     Child 2 Closed
789     Parent  Closed
789     Child 1 Open
789     Child 2 Closed

我一无所获

select UID from TABLE
where  
(TITLE = 'Parent' and Business = 'Closed') 
and
(TITLE like 'Child%' and Business = 'Open')

3 个答案:

答案 0 :(得分:2)

您可以汇总每个UID并使用HAVING来检查是否存在两种情况的记录:

select uid
from TABLE
group by uid  
having count(case when title = 'Parent' and business = 'Closed' then 1 end) > 0
   and count(case when title like 'Child%' and business = 'Open' then 1 end) > 0;

答案 1 :(得分:1)

听起来像您想要将表连接到自身,然后寻找无效的组合:

SELECT DISTINCT t1.UID
FROM Table t1
INNER JOIN Table t2 ON t1.UID = t2.UID
WHERE t1.Title = 'Parent' AND
      t1.Business = 'Closed' AND
      t2.Title LIKE 'Child%' AND
      t2.Business = 'Open'

答案 2 :(得分:0)

尝试通过以下方式使用存在

select t1.* from 
table t1
where t1.Title in ('parent','closed')
and not exists ( select 1 from table t2 where t1.UID=t2.UID  
       and Business='Open' and Title ='Child'  ) 
union 
select * from table 
where Title not in ('parent','closed')