Without any schema context, I can only provide a general structure, but in SQL Server 2008 you should be able to do something like this:
-- This is called a CTE (Common Table Expression)
-- Think of it as a named sub-query
;WITH computed_table AS (
-- The ROW_NUMBER() function produces an ordered computed
-- column ordered by the values in the column specified in
-- the OVER clause
SELECT ROW_NUMBER() OVER(ORDER BY Id) AS row_num
,*
FROM my_table
)
SELECT *
-- perform calculations on t1 and t2
,(t1.amount - t2.amount) AS CalculatedAmt -- example calcuation
FROM computed_table t1
OUTER APPLY (
SELECT *
FROM computed_table t2
WHERE t2.row_num = t1.row_num - 1
) AS prev
The CTE and the ROW_NUMBER()
function are necessary to make sure you have a perfectly ordered column with no gaps, something which can't be guaranteed with a primary key field since rows could be deleted. The OUTER APPLY
allows you to perform a table-valued operation on the individual values of the rows in the left hand table.
EDIT: To insert the results into a table, rather than just selecting them, you can add a INSERT
clause after the SELECT
clause:
...(CTE HERE)...
SELECT *
-- perform calculations on t1 and t2
,(t1.amount - t2.amount) AS CalculatedAmt -- example calcuation
-- This INSERT clause will insert the result set into my_table. Make
-- sure the column aliases in the SELECT clause match the column names
-- in my_table.
INTO my_table
FROM computed_table t1
...(REST OF QUERY HERE)...