看看LAG功能。它會爲你提供你想要的。
類似:
declare @temptable TABLE (case_id varchar(2), row_order int, days_diff float)
INSERT INTO @temptable values ('A',1,5)
INSERT INTO @temptable values ('A',2,3)
INSERT INTO @temptable values ('A',3,2)
INSERT INTO @temptable values ('B',1,5)
INSERT INTO @temptable values ('B',2,1)
--select * from @temptable
SELECT case_id,row_order, LAG(days_diff,1) OVER (PARTITION BY case_id ORDER BY row_order) AS prev_row,days_diff,
CASE
WHEN row_order = 1 THEN days_diff
ELSE LAG(days_diff,1) OVER (PARTITION BY case_id ORDER BY row_order) - days_diff
END AS newcolumn
FROM @temptable
order by case_id,row_order asc
SELECT case_id,row_order,LAG(days_diff,1) OVER (PARTITION BY case_id ORDER BY row_order) AS prev_row, days_diff,
COALESCE(LAG(days_diff,1) OVER (PARTITION BY case_id ORDER BY row_order) - days_diff , days_diff)
FROM @temptable
order by case_id,row_order asc
其他答案將在地方CASE語句的使用聚結。這可能更快,但我覺得這更清楚。
如果您運行並查看執行計劃,它們是相同的。
哪個版本的sql server? – techspider
可能重複[如何減去sql中的前一行?](http://stackoverflow.com/questions/17560829/how-can-i-subtract-a-previous-row-in-sql) – techspider
使用Sql Server 2014.謝謝。 – 0nir