T-sql – Percentage difference of the last value from the previous values of a column based on certain data group within the same table

t-sql

I have a table shown in below image. Actually i want to calculate the percentage difference in this table. The methodology of calculating the difference will be as following.

1-Records are logically grouped by Column2.

2-We want to compare value of column3 with the other records of the group but the column3 value is taken based on the max-value of column 1 in the group.

Table Image

Best Answer

If your version of SQL Server is recent enough (2012+), the problem can be solved with the window/analytic function LAST_VALUE():

Column4 = (LAST_VALUE(Column3) OVER (PARTITION BY Column2 ORDER BY Column1) 
           - Column3) / Column3 * 100

or FIRST_VAUE() with inverse order:

Column4 = (FIRST_VALUE(Column3) OVER (PARTITION BY Column2 ORDER BY Column1 DESC) 
           - Column3) / Column3 * 100