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.
No_ Name Account_Type Subgroup (New_Column) 100 Sales 3 200 Underwear 0 250 *100 300 Bikes 0 250 *100 400 Profit 3 500 Cash 0 450 *400
So for every time there is a value in ‘Subgroup’ I want the (New_Column) to get the value [No_] from the row above
No_ Name Account_Type Subgroup (New_Column) 100 Sales 3 150 TotalSales 3 200 Underwear 0 250 *150 300 Bikes 0 250 *150 400 Profit 3 500 Cash 0 450 *400
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:
Advertisement
Answer
SQL Server 2012 suggests using Window Offset Functions. In this case : LAG
Something like this:
SELECT [No_] ,[Name] ,[Account_Type] ,[Subgroup] ,LAG([No_]) OVER(PARTITION BY [Subgroup] ORDER BY [No_]) as [PrevValue] FROM table
Here is an example from MS: http://technet.microsoft.com/en-us/library/hh231256.aspx