Thread: Re: [NOVICE] Compare rows

Re: [NOVICE] Compare rows

From
"Oliveiros d'Azevedo Cristina"
Date:
 
----- Original Message -----
 

Hi,

I do have order of rows. The problem originally is: I need to set all flag with value 0 to -1 whose next row has flag as 1. This  is to be done for each city separetly, i.e. flag of last row of city A need not be changed due to first row of city B.

City          Date                  Flag                       
A         31-01-1991               0            
A         03-03-1991               1     
A         04-04-1991               0
A         06-08-1991               0
A        13-01-1992                1
A        12-03-1992                1
B        12-01-1988                0
B        19-03-1999               1
B        01-04-1999                0
B        09-06-2001                 1

The dates for a villages are in sorted order.Expected output:


              City                            Date                  Flag                       
                A                        03-03-1991               1      
                A                        31-01-1991               -1      
                A                        04-04-1991               0
                A                         06-08-1991               -1 
                A                         13-01-1992                1
                A                          12-03-1992                1
                B                          12-01-1988                -1
                B                          19-03-1999               1
                B                           01-04-1999                -1
                B                            09-06-2001                 1
                
The (city,Date) is unique for each tuple.Hope I am able to state the problem correctly.
Thanks Lalit

 
* Hi, Lalit,
 
First, please always CC to mailing list. You may get help faster from someone with more "savoir faire" than me.
 
Second,
 
Try this out and tell me if it produced the output you intended
 

UPDATE yourTable
SET "Flag" = -1
FROM
(
SELECT  x."Date" as "Date",x."City" as "City",x."Flag" as "Flag" ,MAX(y."Date")  as anterior
FROM yourTable x
JOIN yourTable y
ON y."City" = x."City"
AND y."Date" < x."Date"
GROUP BY x."Date",x."City",x."Flag"
) umq
WHERE yourTable."City" = umq."City" and anterior = yourTable."Date"
AND yourTable."Flag" = 0
AND umq."Flag" = 1
 
 
HTH,
 
Best,
Oliver