Re: SQL (table transposition) - Mailing list pgsql-sql

From Mark Volpe
Subject Re: SQL (table transposition)
Date
Msg-id 398993D3.D421AAB7@epamail.epa.gov
Whole thread Raw
In response to SQL (table transposition)  (Dana.Reed@clinicaldatacare.com)
List pgsql-sql
Hope you like black magic :)

SELECT IND AS T1_INDEX, MIN(CASE WHEN KEY=1 THEN VALUE ELSE NULL END) AS
KEY1VAL, MIN(CASE WHEN KEY=2 THEN VALUE ELSE NULL END) AS KEY2VAL, MIN(CASE
WHEN KEY=3 THEN VALUE ELSE NULL END) AS KEY3VAL FROM T2 GROUP BY IND ORDER BY
IND;

Mark

Dana.Reed@clinicaldatacare.com wrote:
> 
> Is there any way to get table T3 (below) from T1 and T2 using SQL (select, view, etc)?
> 
> T3 is basically all INDEX values from T1 matched to IND from T2 with the corresponding KEY/VALUE pairs transposed
fromrows to columns.
 
> 
> -------
> |INDEX|   (T1)
> -------
> |  1  |
> |  2  |
> |  3  |
> -------
> 
> -----------------
> |IND|KEY| VALUE |   (T2)
> -----------------
> | 1 | 1 | val_a |
> | 1 | 2 | val_b |
> | 1 | 3 | val_c |
> | 2 | 1 | val_d |
> | 2 | 2 | val_e |
> | 3 | 1 | val_f |
> | 3 | 3 | val_g |
> -----------------
> 
> ----------------------------------
> |T1_INDEX|KEY1VAL|KEY2VAL|KEY3VAL|   (T3)
> ----------------------------------
> |   1    | val_a | val_b | val_c |
> |   2    | val_d | val_e |       |
> |   3    | val_f |       | val_g |
> ----------------------------------
> 
> Thanks for any suggestions
> 
> med vänlig hälsning
> /Dana


pgsql-sql by date:

Previous
From: Mark Volpe
Date:
Subject: Re: PL/pgSQL
Next
From: Alexaki Sofia
Date:
Subject: A question about indexes...