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.
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.
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.
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.
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.
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 |
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With