Click here to Skip to main content
15,916,945 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Dear All,
How to Get Previous Value in table.

Data
ITEMCODE  Date           ISSUE QTY 
1         10/10/2015       20
1         11/10/2015        0
1         13/10/2015       30
1         15/10/2015       30
1         16/10/2015        0 
1         17/10/2015        0
1         118/10/2015      20


I need to replace or change 0 issue qty into Previous Value like below.
ITEMCODE  Date           ISSUE QTY 
1         10/10/2015       20
1         11/10/2015       20
1         13/10/2015       30
1         15/10/2015       30
1         16/10/2015       30 
1         17/10/2015       20
1         118/10/2015      20


Please help me how to fix this?
Posted
Updated 13-Sep-15 10:31am
v2

If I understand your question correctly, in an update statement you want to fetch the value from the previous row. So perhaps something like
SQL
UPDATE MyTable
SET [ISSUE QTY] = (SELECT b.[ISSUE QTY])
                   FROM MyTable b
                   WHERE b.[Date] = (SELECT MAX(c.[Date])
                                     FROM   MyTable c
                                     WHERE  c.[Date] < b.[Date]
                                     AND    c.[ISSUE QTY] <> 0))
WHERE [ISSUE QTY] = 0;
 
Share this answer
 
Comments
Maciej Los 13-Sep-15 16:34pm    
I would recommend to use joins instead of two subqueries. +4 for idea.
You need to update the record where the ISSUE QTY is zero, try the following SQL

C#
"UPDATE table_name SET [ISSUE QTY] = @0 WHERE [ISSUE QTY] = 0";


Then use the methods SQL Parameters (based on the language being used here, C# or VB.NET or what ever language for your platform) and change the value of @0 to a value that needs to be there; either 30 or 20 as per your data. There is no logic that I can use to give you an answer for that.

SQL Parameterization allows you to protect your application from SQL Injections, that are mostly caused by string concatenations and other similar query building procedures.
 
Share this answer
 
v2
The best solution for such of situation is to use UPDATE + SELECT statement in one!
SQL
UPDATE destTable Set Field1 = sourceTable.Field2
FROM Table1 As destTable INNER JOIN Table2 AS sourceTable ON destTable.KeyField = sourceTable.ForeignKeyField
WHERE destTable.FilterField = @Whatever


Change the code to your needs!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900