将前一行值减去当前行

时间:2019-01-10 13:18:07

标签: sql sql-server tsql sql-server-2008

我有下表:

id  value  acc_no 
-----------------
1     12     1 
2     14     1 
3     15     1 
4     10     2 
5     16     2 
6     19     1 
7      7     3 
8     24     2 

预期输出

id  value  acc_no   result 
------------------------------
1     12     1          12(current row values of acc_no=1) 
2     14     1          2(14 (current row values)-12(previous row value of acc_no=1))  
3     15     1          1(15-14) 
4     10     2          10(current row values of acc_no=2) 
5     16     2          6(16 (current row values)-12(previous row value of acc_no=2)) 
6     19     1          4(19(current row values)-15(previous row value of acc_no=1)) 
7     7      3           7(current row values of acc_no=3) 
8     24     2          8(24(current row values)-16(previous row value of acc_no=2)) 

我尝试了以下查询:

select 
    id, value,
    acc_no,
    (value - (select value from tb_acc t1 where t1.id = t.id - 1)) as result 
from 
    tb_acc t

但是我没有得到预期的正确输出

4 个答案:

答案 0 :(得分:3)

B

答案 1 :(得分:1)

使用窗口功能:

def serialize_dummy_recording(filename):
    with open(filename, "wb") as f:
        for serialized_sample in [msgpack.packb({'x': i}) for i in range(10)]:
            f.write(serialized_sample)


def main():
    filename = "test.rec"
    if not os.path.exists(filename):
        serialize_dummy_recording(filename)

    index = index_from_recording(filename)
    print(index)


if __name__ == "__main__":
    main()

答案 2 :(得分:0)

你可以喜欢

选项一:使用 LAG() 功能(我只是注意到您使用的是2008,但我也将其发布给其他读者)

SELECT *,
       Value - LAG(Value, 1, 0) OVER(PARTITION BY acc_no ORDER BY ID) Result
FROM T
ORDER BY ID;

选项二:使用CTE和窗口函数+ ISNULL()

WITH CTE AS
(
  SELECT *,
         ROW_NUMBER() OVER(PARTITION BY acc_no ORDER BY id) RN
  FROM T
)
SELECT T1.id,
       T1.value,
       T1.acc_no,
       T1.value - ISNULL(T2.value, 0) Result
FROM CTE T1 LEFT JOIN CTE T2
     ON T1.acc_no = T2.acc_no
        AND 
        T1.RN = T2.RN + 1
ORDER BY T1.id;

Live Demo

答案 3 :(得分:0)

您只需要一个窗口总和:

SELECT A.* 
FROM TableA AS A
WHERE Cookie IN ( SELECT Cookie
                  FROM TableA 
                  GROUP BY Cookie
                  HAVING COUNT(*) = 1 
                )