我有一个数据库表,其中包含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
感谢您的帮助
答案 0 :(得分:3)
使用LAG/LEAD
窗口功能。
考虑到您希望每Difference
找到type
,请从窗口函数中删除Partition by
select id, piece,
Isnull(lag(piece)over(partition by type order by id) - piece,0) as Diff,
type
From yourtable
如果您在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