仅当满足相似行的另一个条件时才选择行

时间:2017-02-15 14:56:20

标签: sql oracle

表格订单

Status_id Order_number 
100        ord1 
200        ord2 
100        ord3 
300        ord2 
100        Ord4 
400        ord2 
200        ord1
200        ord3

如果相同的订单有Status_id=100,我需要200Status_id=400但所有订单,但不应选择此订单。 在上面的示例中,应选择ord1ord3ord4。但不应选择Ord2,因为status_id=400也是如此。

2 个答案:

答案 0 :(得分:2)

这是一种可以通过group byhaving轻松解决的问题:

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.