根据另一列中的值从一列中减去值 (SQL)
Subtract values from one column based on values in another (TSQL)
我有 table 需要根据应用于另一列的条件减去一列中的值。例如,我想减去代码为 fst
和 trd
的值,意思是 (12 - 23)
。
我不想声明单独的变量。是否可以通过查询来实现?
一种方法是条件聚合:
select sum(case when code = 'fst' then value else - value end)
from t
where code in ('fst', 'trd');
假设每个代码只有一行,您也可以使用 join
:
select tf.value - tt.value
from t tf join
t tt
on tf.code = 'fst' and tt.code = 'trd'
我有 table 需要根据应用于另一列的条件减去一列中的值。例如,我想减去代码为 fst
和 trd
的值,意思是 (12 - 23)
。
我不想声明单独的变量。是否可以通过查询来实现?
一种方法是条件聚合:
select sum(case when code = 'fst' then value else - value end)
from t
where code in ('fst', 'trd');
假设每个代码只有一行,您也可以使用 join
:
select tf.value - tt.value
from t tf join
t tt
on tf.code = 'fst' and tt.code = 'trd'