从两列中减去数据并生成一列

时间:2018-04-05 02:06:10

标签: sql oracle

我有以下数据

id   year   marks    id    year    marks 
1    2017   80       1     2018    100  
2    2017   60       2     2018    70 
3    2017   500      3     2018    600 

我的结果应该是差异列 20,10,100 的值。 所有这些数据都应该在一行中。

4 个答案:

答案 0 :(得分:2)

不知何故,我想你想要:

select id, sum(case when year = 2018 then marks else - marks end) as diff
from t
where year in (2017, 2018)
group by id;

答案 1 :(得分:2)

除非我遗漏了某些内容,否则您只想对两个标记列进行区分:

SELECT
    t1.id, t1.year, t1.marks AS marks_2017, t2.id, t2.year, t2.marks AS marks_2018,
    t2.marks - t1.marks AS diff
FROM yourTable t1
INNER JOIN yourTable t2
    ON t1.id = t2.id AND t1.year = 2017 AND t2.year = 2018;

答案 2 :(得分:0)

SELECT id, year, marks, id, year, new_marks, new_marks - marks AS diff
FROM yourTable where year = '2018'

答案 3 :(得分:0)

select 
t1.*, t2.year, t2.marks, t2.marks - t1.marks as diff
from
test t1
inner join
test t2
on t1.id = t2.id and t1.year = 2017 and t2.year = 2018

Demo