2015-03-25 45 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