Re: [NOVICE] Compare rows - Mailing list pgsql-sql

From Oliveiros d'Azevedo Cristina
Subject Re: [NOVICE] Compare rows
Date
Msg-id 58E9388858734E8E8988EBD9E49E678F@marktestcr.marktest.pt
Whole thread Raw
List pgsql-sql
 
----- 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

pgsql-sql by date:

Previous
From: Wes James
Date:
Subject: Re: Looking for a "show create table " equivalent
Next
From: Jasen Betts
Date:
Subject: Re: Looking for a "show create table " equivalent