簡體   English   中英

從一列中選擇一個不同的變量

[英]Selecting a distinct Variable from one column

這是我的桌子的樣品:

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,因為它有現金和支票付款類型。

您可以使用MINUS set運算符(請參閱文檔 )。 測試表:

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 在這里

使用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>

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;

然后,總項目將等於現金項目的總和。
通過匯總一個案例,您可以算出后面的案例。

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM