0
votes

Does any one know how to create crosstab queries in PostgreSQL? For example I have two following tables:

TABLE A

| ID 1       | ID 2        | ID 3         | 
|:-----------|------------:|:------------:|
| 00001      |        01   |    0001      |
| 00001      |        02   |    0001      |  
| 00001      |        01   |    0002      |

TABLE B

| ID 1       | ID 2        | ID 3         | price        | tax_rate     |
|:-----------|------------:|:------------:|:------------:|:------------:|
| 00001      |        01   |    0001      |5000          | 8            |
| 00001      |        01   |    0001      |6000          | 10           |

I would like the query to return the following crosstab:

| ID 1       | ID 2        | ID 3         | price_8      | price_10     |  
|:-----------|------------:|:------------:|:------------:|:------------:| 
| 00001      |        01   |    0001      |5000          | 6000         | 
| 00001      |        02   |    0001      |null          | null         |
| 00001      |        01   |    0002      |null          | null         |

Is this possible?

2

2 Answers

0
votes

Try this -

SELECT * FROM crosstab(
       'SELECT A.ID1, A.ID2, A.ID3, B.PRICE, B.TAX_RATE 
        FROM A
        LEFT JOIN B
        ON A.ID1 = B.ID1
        AND A.ID2 = B.ID2
        AND A.ID3 = B.ID3') AS
FINAL_RESULT (ID1 TEXT, ID2 TEXT, ID3 TEXT, PRICE_8 NUMERIC, PRICE_9 NUMERIC);
0
votes

Here is a sample for your tables:

SELECT split_part(id, '.', 1) AS id1,
split_part(id, '.', 2) AS id2,
split_part(id, '.', 3) AS id3,
price_8, price_10
FROM crosstab(
  'select id1||''.''||id2||''.''||id3 as id, cast(tax_rate as text) as taxRate, price 
   from (select * from Table1 natural left join Table2
   order by 1,2,3) t'
   )   
AS ct (
  id text, 
  price_8 int,
  price_10 int
  );