Re: [NOVICE] Compare rows

From: "Oliveiros d'Azevedo Cristina" <oliveiros(dot)cristina(at)marktest(dot)pt>
To: "LALIT KUMAR" <lalit(dot)jss(at)gmail(dot)com>
Cc: <pgsql-sql(at)postgresql(dot)org>
Subject: Re: [NOVICE] Compare rows
Date: 2011-07-14 11:30:40
Message-ID: 58E9388858734E8E8988EBD9E49E678F@marktestcr.marktest.pt
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql


----- Original Message -----
From: LALIT KUMAR
To: Oliveiros d'Azevedo Cristina

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

Browse pgsql-sql by date

  From Date Subject
Next Message Craig Ringer 2011-07-14 23:40:11 Re: Looking for a "show create table <name>" equivalent
Previous Message Jasen Betts 2011-07-14 10:22:14 Re: Looking for a "show create table <name>" equivalent