Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL difference between rows

Tags:

I have a SQL 2008 database table like this

name      score ----------------------- steve     207 steve     205 steve     200 steve     139 

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

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

What is the best way to do this? Thanks!

like image 973
cwhelms Avatar asked Jun 09 '11 22:06

cwhelms


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 you find the difference in rows?

Find Row Differences in ExcelClick “Find & Select” and pick “Go To Special” in the drop-down list. In the window that pops open, choose “Row Differences” and click “OK.” The window will automatically close, and you'll see the differences in your rows highlighted.

How do I compare two consecutive rows in SQL?

Here's the SQL query to compare each row with previous row. In the above query, we join sales table with itself using an INNER JOIN condition g2.id=g1.id + 1 that allows you to compare each row with its previous row. Please note, this condition depends on the fact that our id column has consecutive numbers.

How do you subtract rows in SQL?

The SQL MINUS operator is used to return all rows in the first SELECT statement that are not returned by the second SELECT statement. Each SELECT statement will define a dataset. The MINUS operator will retrieve all records from the first dataset and then remove from the results all records from the second dataset.


1 Answers

This is one way to do it

with cte as (SELECT    ROW_NUMBER() OVER (PARTITION BY table.name ORDER BY id) row,    name,    score  FROM table) SELECT     a.name ,    a.score - ISNULL(b.score,0) FROM    cte a    LEFT  JOIN cte b    on a.name = b.name     and a.row = b.row+1 
like image 142
Conrad Frix Avatar answered Sep 22 '22 03:09

Conrad Frix