我不确定SQL是否可以这样,或者不知道如何询问它。如果有类似的结果可用,我试图包括结果:
L# ORDER LINE PART STATUS
------------------------------------
1 005478 1 XB3-001 0
2 005478 1 XB3-001 1
3 005478 1 XB3-001 2
4 005478 2 W3000 0
5 005478 2 W3000 1
6 005478 2 W3000 2
7 005489 1 1734-IB8 0
8 005489 1 1734-IB8 1
9 005489 2 1756-L7 0
10 005489 2 1756-L7 1
11 005489 2 1756-L7 2
我查询订单号和其他一些内容来过滤结果。我想做的是,如果一个条目的0和1,但不是2,则显示“part”的所有行。
因此,在上面的数据中,只应返回L#7和8。
我一直在思考它几个小时,但我没有想出任何好的东西。
实际查询返回12列,但除了否定任何分组解决方案之外,其他列并不真正相关。我使用左连接加入了几个表,但这可能会根据此问题的解决方案而改变。
谢谢!
答案 0 :(得分:0)
Not exists
:
select t.*
from t
where not exists (select 1 from t t2 where t2.order = t.order and t2.part = t.part and t2.status = 2);
如果您想坚持0
和1
都可用,那么让我们增强逻辑:
select t.*
from t
where not exists (select 1 from t t2 where t2.order = t.order and t2.part = t.part and t2.status = 2) and
exists (select 1 from t t2 where t2.order = t.order and t2.part = t.part and t2.status = 0) and
exists (select 1 from t t2 where t2.order = t.order and t2.part = t.part and t2.status = 1);
或者,如果状态仅为0,1和2并且没有重复项且状态1意味着状态0存在,那么您也可以这样做:
select t.*
from t
where 1 = (select max(status)
from t t2
where t2.order = t.order and t2.part = t.part
);
另一种方法使用窗口函数:
select t.*
from (select t.*,
sum(case when status = 2 then 1 else 0 end) over (partition by order, part) as num_status_2
from t
) t
where num_status_2 = 0;
或:
select t.*
from (select t.*,
sum(case when status = 0 then 1 else 0 end) over (partition by order, part) as num_status_0,
sum(case when status = 1 then 1 else 0 end) over (partition by order, part) as num_status_1,
sum(case when status = 2 then 1 else 0 end) over (partition by order, part) as num_status_2
from t
) t
where num_status_2 = 0 and num_status_1 > 0 and num_status_2 > 0;
答案 1 :(得分:0)
怎么样:
select *
from my_table
where "PART" not in (
select "PART"
from my_table
where status = 2
)
and "PART" in (
select "PART"
from my_table
where status = 0
)
and "PART" in (
select "PART"
from my_table
where status = 1
);
答案 2 :(得分:0)
NOT和EXISTS函数的组合将是我在这里使用的。 如果存在行且NOT子句只是翻转条件,则exists函数将匹配。使用这样的exists函数只会返回子查询中不存在与条件匹配的记录的记录。
select *
from Table t1
where not exists (
select ''
from Table t2
where t1.order = t2.order
and t1.part = t2.part
and t2.status = 2
)
and t1.status IN (1, 0)