Home > other >  How to get final result by subtracting all row values of a single column of a Sql table
How to get final result by subtracting all row values of a single column of a Sql table

Time:03-15

I have a amount column in my table.

Amount
22
16
4

How can I subtract in an ascending order i.e(22-16-4) based on date and get final result : 2

CodePudding user response:

Here is a working query for SQL Server:

SELECT TOP 1 val - SUM(val) OVER (ORDER BY val
                                  ROWS BETWEEN UNBOUNDED PRECEDING AND
                                  1 PRECEDING) sum_val
FROM yourTable
ORDER BY val DESC;

Demo

  •  Tags:  
  • sql
  • Related