2017-01-13 70 views
-1

我的結果從查詢中設置看起來像這樣基於特定條件的分組和聚集

trackingnumber type   price 
------------------------------------------ 
12799467   AVRM   674.0536 
12799467   AVRM   860.7415 
12799467   PRICESTD  200.00 
12799468   PRICESTD  590.85 
12799469   PRICESTD  800 
12799470   PRICESTD  640 
12799471   PRICESTD  160 
12799472   PRICESTD  2080 
12799473   PRICESTD  354.3779 

我想團這個由trackingnumber和情況下,分組結果集的計數大於1倍的回報所有priceSUM其中typeAVRM否則返回個別價格。如果計數 更是爲零,他們的都沒有type AVRM那麼它的總價格將是空

預期的結果將是這個

trackingnumber Total Price 
----------------------------------------- 
12799467  1534.7951 --sum of price excluding 200 
12799468  590.85 
12799469  800 
12799470  640 
12799471  160 
12799472  2080 
12799473  354.3779 

我想不出辦法讓這個工作除了由trackingnumber分組並通過在select一部分,但在使用case語句檢查type我相信,因爲我們不組由type

我不是不會工作河畔e如果這可以使用單個查詢來實現。

+3

如果想要什麼就有什麼樣'12799468 PRICESTD 100'另一行哪'price'將ü然後返回行? – Utsav

+2

,以及如果在哪裏是另一行像'123 AVRM 100',因爲這是'trackingnumber'的唯一記錄是否會退還價格。 – Utsav

+0

@Utsav - 如果我們從字面上理解問題,如果只有一行用於跟蹤編號,那麼「按原樣返回單個價格」 - OP的問題陳述中的「else」子句不提及「AVRM」或'不AVRM'。但是第一個問題是:如果對於一個跟蹤數有多行,其中沒有一個具有'AVRM'類型?或者這在現實生活中是不可能的? – mathguy

回答

3

是的,它可以在一個查詢中完成。

with sample_data (tracking_Number, "TYPE", price) as 
( 
SELECT 12799467,'AVRM',674.0536 FROM DUAL UNION ALL 
SELECT 12799467,'AVRM',860.7415 FROM DUAL UNION ALL 
SELECT 12799467,'PRICESTD',200.00 FROM DUAL UNION ALL 
SELECT 12799468,'PRICESTD',590.85 FROM DUAL UNION ALL 
SELECT 12799469,'PRICESTD',800 FROM DUAL UNION ALL 
SELECT 12799470,'PRICESTD',640 FROM DUAL UNION ALL 
SELECT 12799471,'PRICESTD',160 FROM DUAL UNION ALL 
SELECT 12799472,'PRICESTD',2080 FROM DUAL UNION ALL 
SELECT 12799473,'PRICESTD',354.3779 FROM DUAL) 
SELECT tracking_number, 
     case when count(*) > 1 THEN 
      sum(decode("TYPE",'AVRM',price,null)) ELSE 
      sum(price) END price 
from sample_data 
group by tracking_number 
order by tracking_Number; 
0

例如下一個解決方案。我想補充條件exlude類型行不equla「AVRM」如果用「AVRM」 exests

with s (trackingnumber ,type  ,price) 
as (
select 12799467,'AVRM',674.0536 from dual union all 
select 12799467  ,'AVRM',   860.7415 from dual union all 
select 12799467  ,'PRICESTD',  200.00 from dual union all 
select 12799468   ,'PRICESTD',  590.85 from dual union all 
select 12799469   ,'PRICESTD',  800 from dual union all 
select 12799470   ,'PRICESTD',  640 from dual union all 
select 12799471   ,'PRICESTD',  160 from dual union all 
select 12799472   ,'PRICESTD',  2080 from dual union all 
select 12799473   ,'PRICESTD',  354.3779 from dual) 
select trackingnumber, 
     sum(price) 
from (select s.*,rownum as rn from s 
     where not exists (select null 
         from s subs 
       where s.trackingnumber = subs.trackingnumber 
        and s.type != 'AVRM' 
        and subs.type = 'AVRM') 
     ) 
group by trackingnumber, 
      case when type = 'AVRM' then 0 else rn end;