Viraj Kawthankar
Viraj Kawthankar

Reputation: 61

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

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

Upvotes: 1

Views: 97

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521279

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

Upvotes: 3

Related Questions