更新时间:2023-11-29 22:45:40
Try this:select t1.pid, t1.sales, t1.month1, isnull((select t2.sales from table1 t2 where t2.pid = t1.pid - 1) - t1.sales, 0) as differe from table1 t1
Depends on your database and version thereof.
If it's new enough you can use the analytical functionLag
Select Pid, Sales, Month1, LAG(sales, 1, 0) OVER (PARTITION BY Pid ORDER BY Month1) - sales as difference FROM MyTableFor other solutions you need to state your Database and model as it differs a bit between them
<update>
You can also use Row_Number:With ordered as ( Select Pid, Sales, Month1, Row_Number() OVER (PARTITION BY Pid ORDER BY Month1) rn FROM MyTable ) Select O1.Pid, O1.Sales, O1.Month1, O2.Sales - O1.sales as Difference FROM Ordered O1 left outer Join Ordered O2 on O1.rn = O2.rn - 1</update>