2015-09-23 98 views
0

假設有數據象下面這樣:(Oracle)如何根據其他列中的值獲取SUM值?

ID Name Cost 
ID1 A 10  
ID1 A 60  
ID1 B 20 
ID1 C 20 
ID2 B 10 
ID2 B 50 
ID2 C 50 
ID3 B  5 

在這裏,在上表中,ID和NAME不是唯一的。 我想根據NAME以SUM值,因此該預期的結果如下圖所示:

ID A_Costs B_Costs C_Costs AB_Costs 
ID1 70  20  20  90 
ID2    60  50  60 
ID3    5     5 

A_Cost,B_Costs和C_Costs是成本時的名稱是A,B或C. 但是我做當名字是A和B時,如果我想要獲得成本,那該怎麼辦? 所以我試圖做的是:

Select t2.ID, 
SUM(DECODE (t2.name, 'A', t2.Cost, null)), 
SUM(DECODE (t2.name, 'B', t2.Cost, null)) 
--(select sum(t1.cost) from table t1. where t1.name in ('A','B') and t1.id = t2.id) 
from table t2 
group by t2.id 

但是,這是行不通的。 當我的名字是A和B時,我如何獲得成本?有沒有什麼有效的方法在一個查詢中獲得這樣的值?

預先感謝您。

回答

3

如果你想使用decode(),你可以這樣做:

sum(decode(t2.name, 'A', t2.cost, 'B' t2.cost)) 

或者你可以使用一個case聲明:

sum(case when t2.name in ('A', 'B') then t2.cost end) 

全面查詢:

select id, 
     sum(case when name = 'A' then cost end) as a_costs, 
     sum(case when name = 'B' then cost end) as b_costs, 
     sum(case when name = 'C' then cost end) as c_costs, 
     sum(case when name IN ('A', 'B') then cost end) as ab_costs 
    from SomeTable 
group by id 
order by id 

SQL Fiddle Demo

0

在內部查詢中使用sum之後,您還必須進行聚合。

select 
id, max(a_cost) as A_Costs, max(b_cost) as B_Costs, 
max(c_cost) as C_Costs, nvl(max(a_cost),0) + nvl(max(b_cost),0) as AB_Costs 
from (
select ID, 
sum(case when name = 'A' then cost end) as a_cost, 
sum(case when name = 'B' then cost end) as b_cost, 
sum(case when name = 'C' then cost end) as c_cost 
from table 
group by id 
) t 
group by id