从一列中选择一个不同的变量

时间:2018-05-15 20:32:55

标签: sql oracle

以下是我的表格样本:

Order_id    Item_id Payment_type
2345        120     Cash  
2345        121     Cash    
3346        122     Cash    
3346        123     Check    
3346        124     Check    
4456        125     Check
4456        126     Check    
5456        127     Cash

一个订单可以包含一个或多个商品以及一种或多种付款方式。 但在我的结果中,我希望订单ID只有现金作为付款方式。 所以在上表中,我的结果应该只有2345和5456。

我试过

Select order_id
from orders
where (payment_type = 'Cash' and payment_type <> 'Check')

但结果是2345,3346和5456。

我不希望3346在我的结果中,因为它有现金和支票类型。

4 个答案:

答案 0 :(得分:1)

您可以使用MINUS集合运算符(请参阅documentation)。 测试表:

create table T as
select 2345 Order_id, 120 Item_id, 'Cash' Payment_type from dual union all
select 2345, 121, 'Cash' from dual union all
select 3346, 122, 'Cash'  from dual union all
select 3346, 123, 'Check' from dual union all
select 3346, 124, 'Check' from dual union all
select 4456, 125, 'Check' from dual union all
select 4456, 126, 'Check' from dual union all
select 5456, 127, 'Cash'  from dual;

查询

select order_id
from T
minus
select order_id
from T
where payment_type = 'Check'
;

--result
ORDER_ID  
2345      
5456 

Dbfiddle here

答案 1 :(得分:1)

使用GROUP BYHAVING子句的选项:

SQL> with test as
  2  (select 2345 order_id, 120 item_id, 'Cash' payment_type from dual union all
  3   select 2345, 121, 'Cash'  from dual union all
  4   select 3346, 122, 'Cash'  from dual union all
  5   select 3346, 123, 'Check' from dual union all
  6   select 3346, 124, 'Check' from dual union all
  7   select 4456, 125, 'Check' from dual union all
  8   select 4456, 126, 'Check' from dual union all
  9   select 5456, 127, 'Cash'  from dual
 10  )
 11  select order_id
 12  from test
 13  group by order_id
 14  having min(payment_type) = max(payment_type)
 15    and min(payment_type) = 'Cash';

  ORDER_ID
----------
      5456
      2345

SQL>

答案 2 :(得分:0)

WHERE适用于每条记录。因此,对于WHERE,您无法确定一条记录是否与“现金”匹配,而且没有一条与“支票”匹配。您必须按订单ID进行汇总,并使用HAVING

select order_id
from orders
group by order_id
having count(case when payment_type = 'Cash' then 1 end) > 0
   and count(case when payment_type = 'Check' then 1 end) = 0
order by order_id;

答案 3 :(得分:0)

然后总项目将等于总现金项目 通过总结CASE,您可以计算后者。

select order_id
from orders
group by order_id
having count(*) = sum(case payment_type when 'Cash' then 1 else 0 end)

或者通过总结DECODE

select order_id
from orders
group by order_id
having count(*) = sum(decode(payment_type,'Cash',1,0))