Skip to content
Advertisement

How to get the value using another column and get difference between each row in MySQL or SQL?

I have above two columns(finish_position, official_rating). I want get the above values for the difference column. Whenever finish_position is 1 then difference is 0. All above rows differences are 0 until this row (first row from top to bottom that finish_position is equal to 1) You can get the idea from the above table. I need to get the difference between each rows official_rating between the finish_positions are equal to 1. I hope you guys are understand the problem and please help me to do this.

I want the SQL code.

Advertisement

Answer

I have imagined to do it like this and I will try to explain.

Please note that my date column is named datec and table is called test

  • First I have selected selected first part of the result where I will not calculate any difference (until first number 1 appeared). I did it with this query:

  • Then I have selected the second part of the table, where I will calculate the difference and mark it as null because i will calculate the difference in the outer query. The second part is selected with this query:

  • And finally I have made an union of this two results and wrote a query on it:

Finally I have created a small demo for you (I did not entered whole data but…). Take a look…

After some more discussion with OP I have finally finished with this code:

Here is the second DEMO

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement