Skip to content
Advertisement

How to select info from row above?

I want to add a column to my table that is like the following: This is just an example of how the table is structured, the real table is more than 10.000 rows.

So for every time there is a value in ‘Subgroup’ I want the (New_Column) to get the value [No_] from the row above

There are cases where the table is like the above, where two “Headers” are above. And in that case I also want the first above row (150) in this case.

Is this a case for a cursor or what do you recommend?

The data is ordered by No_

–EDIT–

Starting from the first line and then running through the whole table: Is there a way I can store the value for [No_] where [Subgroup] is ”? And following that insert this [No_] value in the (New_Column) in each row below having value in the [Subgroup] row. And when the [Subgroup] row is empty the process will keep going, inserting the next [No_] value in (New_Column), that is if the next line has a value in [Subgroup]

Here is a better image for what I´m trying to do: enter image description here

Advertisement

Answer

SQL Server 2012 suggests using Window Offset Functions. In this case : LAG

Something like this:

Here is an example from MS: http://technet.microsoft.com/en-us/library/hh231256.aspx

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