Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find difference between two rows with conditions

Tags:

oracle

name      point
----------
steve     207
Mary      203
steve     205
steve     200
steve     139
Mary      300

I want to get the difference between the rows with condition eqn = [ (row + 1) - row] where name = steve, so I would ideally want it to be,

steve 2   //207 - 0
steve 5   //205 - 207
steve 61  //200 - 205
steve 139 //139 - 200

there are codes available to find the difference between consecutive rows. but it will not work when condition is added.

like image 408
user1816507 Avatar asked Nov 11 '12 19:11

user1816507


People also ask

How do I find the difference between two rows in SQL?

In the blue text, you can see the calculation of the SQL delta between two rows. To calculate a difference, you need a pair of records; those two records are “the current record” and “the previous year's record”. You obtain this record using the LAG() window function.

How do I compare two rows in a data frame?

The compare method in pandas shows the differences between two DataFrames. It compares two data frames, row-wise and column-wise, and presents the differences side by side. The compare method can only compare DataFrames of the same shape, with exact dimensions and identical row and column labels.

Can we compare two rows in SQL?

Comparing rows of the same table. In the example, we are comparing the immediate rows to calculate the sales made on a day by comparing the amounts of two consecutive days. Syntax for inner join : SELECT column_name(s) FROM table1 t1 INNER JOIN table1 t2 on t1. column1 = t2.

How do I subtract two records 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.


1 Answers

Edited due OP comment I have changed query to match exactly your request.

LAG can helps you:

  select name, 
    coalesce( 
        point - lag( point , 1, Null ) over (order by point),
        point)
    as diff,
    point || '-' ||
    LEAD( point , 1, 0 ) over (order by point) as prev_point
  from t   
  where name = 'steve'  
  order by point desc

Results:

|  NAME | DIFF | PREV_POINT |
-----------------------------
| steve |    2 |      207-0 |
| steve |    5 |    205-207 |
| steve |   61 |    200-205 |
| steve |  139 |    139-200 |
like image 99
dani herrera Avatar answered Oct 04 '22 15:10

dani herrera