从数据中减去所有值

时间:2009-12-21 08:35:53

标签: sql sql-server sql-server-2005 tsql

表格数据如下所示

id val
1 4
2 2
3 1

我想在一个sql语句中减去val字段的值的结果。 喜欢它应该像 4-2-1 = 1如果按id asc订购,1-2-4 = -5如果订购ID desc

3 个答案:

答案 0 :(得分:2)

你可以试试这个

DECLARE @Table TABLE(
        ID INT,
        Val INT
)

INSERT INTO @Table (ID,Val) SELECT 1, 4
INSERT INTO @Table (ID,Val) SELECT 2, 2
INSERT INTO @Table (ID,Val) SELECT 3, 1

SELECT  SUM(Val * CASE WHEN RowID = 1 THEN 1 ELSE -1 END)
FROM    (
            SELECT  *,
                    ROW_NUMBER() OVER (ORDER BY ID) RowID
            FROM    @Table
        ) sub

答案 1 :(得分:1)

您可以声明一个变量并在select语句中递增它:

declare @sum float

select @sum = case when @sum is null then value else @sum - value end
from YourTable
order by id

select @sum

要反转减法顺序,请将order by id更改为order by id desc

答案 2 :(得分:1)

如果你只想使用没有临时表或变量的sql:

选择fromid.val - sumid.val

来自(

选择val

来自t

其中id =(

    select min(id)

    from t

  )

)fromid交叉连接(

select sum(val) as val

from t

where id > (

      select min(id)

      from t

    )

)sumid