Subtracting one row of data from another in SQL

前端 未结 7 753
抹茶落季
抹茶落季 2020-12-09 19:06

I\'ve been stumped with some SQL where I\'ve got several rows of data, and I want to subtract a row from the previous row and have it repeat all the way down.

So her

7条回答
  •  情深已故
    2020-12-09 19:39

    I had this problem and it was interesting to look at your solutions. I find it strange that such a normal-life problem is so complicated in SQL. As I need the values in a report only, I chose a completely different solution. I'm running Ruby on Rails as the front end of my sqlite3 database, and just did the subtraction in the view like this:

    In your ruby controller, there is a object variable @foo that holds the rows returned by your query.

    In the view, just do

    
    
    <% for i in 0..@foo.length-1 do %>
      
    <% end %>
    
    id length difference
    <%=h @foo[i].id %> <%=h @foo[i].length %> <% if (i==@foo.length-1) then %> <%= @foo[i].length %> <% else %> <%= @foo[i+1].length.to_i - @foo[i].length.to_i %> <% end %>

    Seems to be more robust than the SQL solutions.

提交回复
热议问题