Re: Rename entries with an increment

From: Merlin Moncure <mmoncure(at)gmail(dot)com>
To: JimmyJ <rdinh(at)hotmail(dot)fr>
Cc: pgsql novice <pgsql-novice(at)postgresql(dot)org>
Subject: Re: Rename entries with an increment
Date: 2014-10-01 15:48:59
Message-ID: CAHyXU0xnJ0VnJZtLDT_WVZY+M8A0=nZzxRwHW9URUn150-3woQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

On Wed, Oct 1, 2014 at 5:46 AM, JimmyJ <rdinh(at)hotmail(dot)fr> wrote:
> Hi, here is my issue. I have a table containing names. If a name appears
> several times, I would like to rename it to add an incremented number to it.
> For example, if 'Peter' appears three times in the table, I would like to
> rename the first 'Peter' entry to 'Peter-1', the second one to 'Peter-2' and
> so on. However, I began to do something but this doesn't seem to work at all
> ^^. Could someone please help me ? Thanks :)
>
>
> DECLARE num int;
>
> UPDATE test.suscribers
> SET p_name = CONCAT(p_name,'-',num)
> WHERE p_name=
> (
> SELECT name
> FROM
> (
> SELECT *
> FROM
> (
> SELECT test.suscribers.p_name AS nom, COUNT(*) AS nb
> FROM test.suscribers
> GROUP BY test.suscribers.p_name
> )
> AS table1
> WHERE nb>1 AND wagaa != ''
> )
> AS table2
> )

This is pretty easy with a window function as long as you have a
unique identifier for ordering and updating.

UPDATE test.suscribers.p_name SET p_name =
concat(test.suscribers.p_name || '-' || q.num)
FROM
(
SELECT p_name, row_number() OVER(PARTITION BY p_name ORDER BY id)
AS num -- try this inner query first, replace 'id' with whatever
field(s) are unique
)
WHERE test.suscribers.id = q.id;

merlin

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Kevin Le Gouguec 2014-10-08 09:18:35 [pg_restore] Triggers handling
Previous Message JimmyJ 2014-10-01 10:46:56 Rename entries with an increment