根据 ID 和组减去值

Subtraction of values based on IDs and group after

我正在使用 Oracle。

table 为:

Year   Type   Value
2011   1       500
2011   2       550
2011   3       600
...
...
2012   1       600
2012   2       750
2012   3       930

我需要减去不同类型的所有值,按年份分组。 该操作将是:

2011 -> 1-2-3 (500-550-600)

2012 -> 1-2-3 (600-750-930)

对于...

结果应该是:

Year   Value
2011   -650  
2012   -1080 
...    ...  

我只是没能使这个查询正常工作..

使用条件聚合:

select sum(case when type = 1 then value else - value end) as value
from table t
group by year;

你的意思是 GROUP BY, CASE 决定符号 + 对于类型 1,- 对于其他类型:

select "year", 
       SUM(case when type = 1 then value else -value end)
from yourtable
group by "year"