Click here to Skip to main content
15,920,508 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
ID  VAL CNT
1-  45	-5
2-  40	-8
3-  30	-9
4-  78	-6
5-  88	-4
6-  0   -0
7-  0	-0
8-  0   -0
9-  45	-8
10- 83  -9
11- 0   -0


I want to update the all the VAL column where CNT is 0 with its previous value where where CNT > 0.So, the o/p should be :

ID  VAL CNT
1-  45	-5
2-  40	-8
3-  30	-9
4-  78	-6
5-  88	-4
6-  88  -0
7-  88	-0
8-  88  -0
9-  45	-8
10- 83  -9
11- 83  -0


I know it is a silly question,but i am stuck.
Any help?
Thanks
Posted
Updated 29-Jun-15 0:59am
v2
Comments
CHill60 27-Jun-15 10:43am    
I'm not posting this as a solution as I couldn't get it to work and I'm rushing now to catch a plane! However, I think you need to use the LAG and MERGE functions/methods. Something like
MERGE INTO yourTable USING
(SELECT
ID, LAG(VAL,1) over(ORDER BY ID) previous_VAL
FROM yourTable ) CT ON (CP.ID=CT.ID)
WHEN MATCHED THEN UPDATE SET yourTable.VAL = CT.previous_VAL;

1 solution

Here's a select that will give you the values needed, now you just need to merge them.
SQL
WITH connected as (
    SELECT  ID
           ,LAG(ID,1) OVER(ORDER BY ID) PREVID
           ,VAL
           ,CNT
    FROM    Table1
    )
,CTE(ID,VAL,CNT) as (    
    SELECT  ID
           ,VAL
           ,CNT
    FROM    connected
    WHERE   PREVID IS NULL
    UNION ALL
    SELECT  c.ID
           ,NVL(NULLIF(c.VAL,0),CTE.VAL) VAL
           ,c.CNT
    FROM    connected c
    JOIN    CTE
        ON  CTE.ID = c.PREVID
    )
SELECT  ID,VAL,CNT
FROM    CTE
 
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