我的行看起来像。
OrderNo OrderStatus SomeOtherColumn
A 1
A 1
A 3
B 1 X
B 1 Y
C 2
C 3
D 2
我想返回所有只有一个ordertatus值的订单。例如,这里订单B只有订单状态1 SO结果应该是
B 1 X
B 1 Y
注意:
答案 0 :(得分:2)
您可以使用not exists
:
select t.*
from t
where not exists (select 1
from t t2
where t.orderno = t2.orderno and t.OrderStatus = t2.OrderStatus
);
如果您只想要这样的订单,可以使用group by
和having
:
select orderno
from t
group by orderno
having min(OrderStatus) = max(OrderStatus);
如果您只想要状态1,请将max(OrderStatus) = 1
添加到having
子句。
答案 1 :(得分:1)
OrderStatus
分区的 Count不同OrderNo
,仅显示数字等于1的行:
select OrderNo, OrderStatus, SomeOtherColumn
from ( select t.*, count(distinct orderstatus) over (partition by orderno) cnt
from t )
where cnt = 1
<强> SQLFiddle demo 强>
答案 2 :(得分:1)
这是一种方法。它不处理状态为NULL的情况;如果可能的话,你需要解释你希望如何处理它。
SQL> create table test_data ( orderno, status, othercol ) as (
2 select 'A', 1, null from dual union all
3 select 'A', 1, null from dual union all
4 select 'A', 3, null from dual union all
5 select 'B', 1, 'X' from dual union all
6 select 'B', 1, 'Y' from dual union all
7 select 'C', 2, null from dual union all
8 select 'C', 3, null from dual union all
9 select 'D', 2, null from dual
10 );
Table created.
SQL> variable input_status number
SQL> exec :input_status := 1
PL/SQL procedure successfully completed.
SQL> column orderno format a8
SQL> column othercol format a8
SQL> select orderno, status, othercol
2 from (
3 select t.*, count(distinct status) over (partition by orderno) as cnt
4 from test_data t
5 )
6 where status = :input_status
7 and cnt = 1
8 ;
ORDERNO STATUS OTHERCOL
-------- ---------- --------
B 1 X
B 1 Y
处理NULL状态的一种方法(如果可能发生),如果在这种情况下应拒绝orderno
(未包括在输出中),则以不同方式定义cnt
:
count(case when status != :input_status or status is null then 1 end)
over (partition by orderno) as cnt
并在外部查询中将WHERE子句更改为单个条件
where cnt = 0
答案 3 :(得分:0)
只是想使用统计功能为戈登的答案添加一些内容:
select orderno
from t
group by orderno
having variance(orderstatus) = 0;