计算两个值之间的差异

时间:2017-09-28 15:13:31

标签: sql sql-server

我有桌子'计数'柱

ID    count  OperationID 
100   111      1
99    55       1
94    55       1
90    66       1 
100   69       2
99    33       2
94    33       2
90    47       2
100   777      3
99    55       3
94    31       3
90    12       3

我需要计算两个Id计数之间的差异。需要比较此ID的ID和值。防爆。比较ID 100和ID 99. EX。对于ID 100> ID 99(111> 55)的计数显示56(两个值之间的差异)。对于ID 99>计数为ID 94(55 = 55)显示0等。我该怎么做?

2 个答案:

答案 0 :(得分:1)

这是你想要的吗?

select operation_id, (t100.count - t99.count) as diff
from t t100 join
     t t99
     on t100.operation_id = t99.operation_id and
        t100.id = 100 and t99.id = 99;

如果您只想与所有行的“上一个”值有所不同,请使用lag()

select t.*,
       (t.count - lag(t.count) over (partition by t.operation_id order by t.id)) as diff
from t;

答案 1 :(得分:1)

将Cross Apply与子句一起使用:

    Create table #test ([ID] int, [count] int, [OperationID] int)

    insert into #test values(100, 111, 1)
    insert into #test values(99 , 55 , 1)
    insert into #test values(94 , 55 , 1)
    insert into #test values(90 , 66 , 1) 
    insert into #test values(100, 69 , 2)
    insert into #test values(99 , 33 , 2)
    insert into #test values(94 , 33 , 2)
    insert into #test values(90 , 47 , 2)
    insert into #test values(100, 777, 3)
    insert into #test values(99 , 55 , 3)
    insert into #test values(94 , 31 , 3)
    insert into #test values(90 , 12 , 3)

    select t1.[OperationID], t1.[ID], t2.[ID], t1.count, t2.count, t1.count - t2.count as Diff
    from #test t1
    cross apply #test t2
    where t1.OperationID = t2.OperationID and t1.ID <> t2.ID
    order by t1.OperationID, t1.[ID], t2.[ID]