简体   繁体   English

从两列中减去数据,然后得出一列。

[英]subtract data from two columns and result into one column.`

I have data like below 我有如下数据

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

My result should be values as 20, 10, 100 in Difference column . 我的结果应该是值20,10,100差异列 All this data should be in a single row. 所有这些数据应放在一行中。

Somehow, I think you want: 我想以某种方式想要:

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

Unless I'm missing something, you just want to take a difference of the two marks columns: 除非我遗漏了什么,否则您只想对两个标记列做些不同:

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;
SELECT id, year, marks, id, year, new_marks, new_marks - marks AS diff
FROM yourTable where year = '2018'
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 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 SQL 两个结果来自两列中的一列 - SQL Two result from one column in 2 columns 从两列插入一列数据 - Insert into one column data from two columns 从两个不相关的表中减去列数据 - Subtract column data from two unrelated tables 从两列中减去日期时间并将结果作为整数放在第三列 - Subtract datetime from two columns and put result as integer in third 同一列中有两列数据。 如何正确格式化此表? - Two Columns of data in the same Column. How do I format this table correctly? 带有4个bool列和1个int列的sql表。 如何将一个int中的所有布尔值加在一起 - sql table with 4 bool columns and 1 int column. How to add all bools from one int together 如何将一列结果中的数据分成多列? - How to separate data from one column result into multiple columns? 我想将两列组合成一个新列,但前提是其中一列不为空,然后按该新列排序。 (MySQL) - I want to combine two columns into a new column, but only if one isn't blank, and then sort by that new column. (MySQL) 如何将具有相同数据类型的两个不同列的结果放在一列中,以使两个表中的两行在目标表中都是唯一的 - How to put the result of two different columns with same data type within one column such that both rows from both tables are unique in target table 从两个表中减去列 - Subtract columns from two tables
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM