Re: Flattening a kind of 'dynamic' table

From: Joe Conway <mail(at)joeconway(dot)com>
To: Alexandre Leclerc <alexandre(dot)leclerc(at)gmail(dot)com>
Cc: Dawid Kuroczko <qnex42(at)gmail(dot)com>, PERFORM <pgsql-performance(at)postgresql(dot)org>
Subject: Re: Flattening a kind of 'dynamic' table
Date: 2005-01-28 16:34:27
Message-ID: 41FA6993.5000702@joeconway.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-performance

Alexandre Leclerc wrote:
>>>>>Here a normal listing of design.product_department_time:
>>>>> product_id | department_id | req_time
>>>>>------------+---------------+----------
>>>>> 906 | A | 3000
>>>>> 906 | C | 3000
>>>>> 906 | D | 1935
>>>>> 907 | A | 1500
>>>>> 907 | C | 1500
>>>>> 907 | D | 4575
>>>>> 924 | A | 6000
>>>>> 924 | C | 1575

Sorry for jumping in on this thread so late -- I haven't been able to
keep up with the lists lately.

If I understand what you want correctly, you should be able to use
crosstab from contrib/tablefunc:

create table product_department_time(product_id int, department_id text,
req_time int);
insert into product_department_time values(906, 'A', 3000);
insert into product_department_time values(906, 'C', 3000);
insert into product_department_time values(906, 'D', 1935);
insert into product_department_time values(907, 'A', 1500);
insert into product_department_time values(907, 'C', 1500);
insert into product_department_time values(907, 'D', 4575);
insert into product_department_time values(924, 'A', 6000);
insert into product_department_time values(924, 'C', 1575);

select * from crosstab(
'select product_id, department_id, req_time
from product_department_time order by 1',
'select ''A'' union all select ''C'' union all select ''D'''
) as (product_id int, a int, c int, d int);

product_id | a | c | d
------------+------+------+------
906 | 3000 | 3000 | 1935
907 | 1500 | 1500 | 4575
924 | 6000 | 1575 |
(3 rows)

You could make this dynamic for new values of department_id by wrapping
it with a PL/pgSQL function.

HTH,

Joe

In response to

Responses

Browse pgsql-performance by date

  From Date Subject
Next Message Christopher Weimann 2005-01-28 16:54:57 Re: PostgreSQL clustering VS MySQL clustering
Previous Message Tom Lane 2005-01-28 16:23:16 Re: Poor Performance on Postgres 8.0