Re: PostgreSQL add id column that increments based on data

From: DerekW <derek(at)cmainfo(dot)co(dot)za>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: PostgreSQL add id column that increments based on data
Date: 2014-08-04 08:35:18
Message-ID: 1407141318770-5813661.post@n5.nabble.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Thank you for the input.

I have come up with the following solution:

CREATE TABLE data_raw (
raw_data TEXT
);

COPY data_raw FROM 'C:\path\data_x.txt' ...; -- Repeated for each file

ALTER TABLE data_raw
ADD COLUMN pk_id serial,
ADD COLUMN id integer,
ADD COLUMN indicator integer;

UPDATE data_raw SET
indicator = CAST(substr(raw_data, 1, 1) AS integer),
raw_data = substr(raw_data, 2);

CREATE TABLE id_base AS
SELECT
pk_id,
sum(CASE WHEN indicator = 1 THEN 1 ELSE 0 END) OVER (ORDER BY pk_id) AS
rec_id
FROM data_raw;

CREATE INDEX id_base_pk ON id_base USING btree(pk_id);

UPDATE data_raw r SET
id = (SELECT rec_id FROM id_base b WHERE b.pk_id = r.pk_id);

DROP TABLE id_base;

--
View this message in context: http://postgresql.1045698.n5.nabble.com/PostgreSQL-add-id-column-that-increments-based-on-data-tp5813514p5813661.html
Sent from the PostgreSQL - sql mailing list archive at Nabble.com.

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Marcin Krawczyk 2014-08-05 11:28:29 function call
Previous Message David G Johnston 2014-08-01 16:12:49 Re: PostgreSQL add id column that increments based on data