Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I subtract a previous row in sql?

Tags:

sql-server

vb6

What should I query if I wanted to subtract the current row to the previous row. I will use it on looping in vb6. Something Like this:

Row
1
2
3
4
5

On first loop value 1 will not be deducted because it has no previous row, which is ok. Next loop value 2 will then be deducted by the previous row which is value 1. And so on until the last row.

How can I achieve this routine? By SQL query or VB6 code.Any will do.

like image 419
ImTheBoss Avatar asked Jul 10 '13 01:07

ImTheBoss


People also ask

How do I subtract a row from a previous row?

You can also do this with row_number() : with cte as ( select col, row_number() over (order by id) as seqnum from t ) select t. col, t. col - coalesce(tprev.

How do you subtract a record in SQL?

The Minus Operator in SQL is used with two SELECT statements. The MINUS operator is used to subtract the result set obtained by first SELECT query from the result set obtained by second SELECT query.

How do you subtract a value from a row?

Right-click the row number of row 24. Select 'Paste Special...' from the context menu. Select Subtract, then click OK.

How do I select a previous row in SQL?

1) You can use MAX or MIN along with OVER clause and add extra condition to it. The extra condition is "ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING" which will fetch previous row value. Check this: SELECT *,MIN(JoiningDate) OVER (ORDER BY JoiningDate ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS EndDate.


1 Answers

Assuming you have an ordering column -- say id -- then you can do the following in SQL Server 2012:

select col,
       col - coalesce(lag(col) over (order by id), 0) as diff
from t;

In earlier versions of SQL Server, you can do almost the same thing using a correlated subquery:

select col,
       col - isnull((select top 1 col
                     from t t2
                     where t2.id < t.id
                     order by id desc
                    ), 0)
from t

This uses isnull() instead of coalesce() because of a "bug" in SQL Server that evaluates the first argument twice when using coalesce().

You can also do this with row_number():

with cte as (
      select col, row_number() over (order by id) as seqnum
      from t
     )
select t.col, t.col - coalesce(tprev.col, 0) as diff
from cte t left outer join
     cte tprev
     on t.seqnum = tprev.seqnum + 1;

All of these assume that you have some column for specifying the ordering. It might be an id, or a creation date or something else. SQL tables are inherently unordered, so there is no such thing as a "previous row" without a column specifying the ordering.

like image 159
Gordon Linoff Avatar answered Sep 20 '22 08:09

Gordon Linoff