2015-03-25 47 views
1

我有一个数据库表,其中有2列命名片和diff和类型。从单列中减去数据

这里的表是什么样子

id | piece | diff | type 
1 | 20 | NULL | cake 
2 | 15 | NULL | cake 
3 | 10 | NULL | cake 

我要像20 - 15 = 5,然后15 -10 = 5,那么等等等等堡垒型为其中。

结果会是这样

id | piece | diff | type 
1 | 20 | 0 | cake 
2 | 15 | 5 | cake 
3 | 10 | 5 | cake 

下面的代码我有这么远,但我不认为我是在正确的轨道上

SELECT 
    tableblabla.id, 
    (tableblabla.cast(pieces as decimal(7, 2)) - t.cast(pieces as decimal(7, 2))) as diff 
FROM 
    tableblabla 
INNER JOIN 
    tableblablaas t ON tableblabla.id = t.id + 1 

感谢您的帮助

回答

3

使用LAG/LEAD窗口功能。

考虑,你想找到Differencetype从别的窗口函数

select id, piece, 
     Isnull(lag(piece)over(partition by type order by id) - piece,0) as Diff, 
     type 
From yourtable 

删除Partition by如果使用Sql Server之前2012使用此。

;WITH cte 
    AS (SELECT Row_number()OVER(partition by type ORDER BY id) RN,* 
     FROM Yourtable) 
SELECT a.id, 
     a.piece, 
     Isnull(b.piece - a.piece, 0) AS diff, 
     a.type 
FROM cte a 
     LEFT JOIN cte b 
       ON a.rn = b.rn + 1