2013-10-14 127 views
2

我在SQL Server中有下列名为table1的表。减去两行

id value 
1 10 
2 100 
3 20 
4 40 
5 50 

当我执行查询以下查询它给我造成的110预计

SELECT SUM(value) from table1 where id in (1,2) 

我要的是SUM相反意味着输出应该是90或-90。

我知道这可以通过写下面的查询

select ((SELECT value from table1 where id in (1)) - (SELECT value from table1 where id in (2))) 

做,但没有任何简单的方式来做到这一点(类似SUM函数)。

回答

2

Fiddle demo使用Sum()Case

Declare @SubId int =1 

--To get -90 or +90 change the value of @SubId from 1 to 2 
Select Sum(Case When Id = @SubId Then value Else -1*Value End) Total 
From Table1 
Where Id in (1,2); 
+0

这不是我想要的..我做了我的计算,但这是最接近的,所以我接受这个答案.. thx – Dhaval

0

根据您是否想造成为非负或非正的,你可以在下面的语句切换MIN和MAX:

select max(value) - min(value) 
    from table1 
where id in (1,2)