表格订单
Status_id Order_number
100 ord1
200 ord2
100 ord3
300 ord2
100 Ord4
400 ord2
200 ord1
200 ord3
如果相同的订单有Status_id=100
,我需要200
或Status_id=400
但所有订单,但不应选择此订单。
在上面的示例中,应选择ord1
,ord3
,ord4
。但不应选择Ord2
,因为status_id=400
也是如此。
答案 0 :(得分:2)
这是一种可以通过group by
和having
轻松解决的问题:
select order_number
from orders
group by order_number
having sum(case when status in (100, 200) then 1 else 0 end) > 0 and
sum(case when status = 400 then 1 else 0 end) = 0;
答案 1 :(得分:2)
如果您需要每行的完整详细信息,而不仅仅是订单号,那么您需要使用分析函数而不是聚合;在这种情况下,对test_data=400
。
with
test_data ( status_id, order_number ) as (
select 100, 'ord1' from dual union all
select 200, 'ord2' from dual union all
select 100, 'ord3' from dual union all
select 300, 'ord2' from dual union all
select 100, 'ord4' from dual union all
select 400, 'ord2' from dual union all
select 200, 'ord1' from dual union all
select 200, 'ord3' from dual
)
-- end of test data (not part of the query); SQL query begins below this line
select status_id, order_number
from ( select status_id, order_number,
count(case when status_id = 400 then 1 end)
over (partition by order_number) as st_400_cnt
from test_data
)
where status_id in (100, 200)
and st_400_cnt = 0
order by order_number, status_id -- if needed
;
STATUS_ID ORDER_NUMBER
--------- ------------
100 ord1
200 ord1
100 ord3
200 ord3
100 ord4
5 rows selected.