简体   繁体   中英

SQL How to subtract one column based on criteria from another column

I am trying to subtract this data based on year in the other column to make a new column.
The data looks like this:

+-----+-----+
|value|year|
+-----+-----+
| 2658| 2020|
| 4234| 2019|
| 5435| 2018|
+-----+-----+

And I would like to get an output like this, from say the 2019 - 2020 values:

+---------+
|new_value|
+---------+
| 1576| 
+--------+

I would also not like to make a new tables or anything. Also preferably using CTEs or a way to put into a larger query easily .

You can use conditional aggregation:

select sum(case when year = 2019 then value else - value end)
from t
where year in (2019, 2020);

something like this (untested):

SELECT l.value - r.value as new_value
FROM my_table l 
JOIN my_table r ON (l.year=2019 AND r.year=2020)

Presuming you don't just want 2019/2020, join the table to itself using an off by one join

SELECT b.value - a.value 
FROM t a
  JOIN t b ON a.year + 1 = b.year

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM