(Oracle)如何根据其他列中的值获取SUM值?

时间:2015-09-23 17:22:02

标签: sql oracle

假设有如下数据:

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,我如何获得成本,就像我注释掉的那一行一样?有没有有效的方法可以在一个查询中获得这样的值?

提前谢谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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