Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL Server – calculated column

I need to create a column in a view which is derived as below.

The calculated column is derived from Amount column where a row value is derived by subtracting from previous row value of Amount, and every 1st contract that starts will have no value as it’s the first row of that contract.

Can someone please suggest what option I have to achieve this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Contract DateValue Amount Calculated Column
111 20-June-2023 100
111 21-June-2023 150 50
111 21-June-2023 250 100
111 21-June-2023 200 50
222 20-June-2023 300
222 21-June-2023 350 50
222 22-June-2023 450 100
333 23-June-2023 100
333 24-June-2023 200 100
333 24-June-2023 250 50

Any suggestions are welcome.

>Solution :

This is a way to do it using window function LAG() to get the previous value :

select *, Amount - lag(Amount) over (partition by Contract order by DateValue) as [Calculated Column]
from mytable

Demo here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading