Answer the question
In order to leave comments, you need to log in
How to transform a table in PostgreSQL?
I have a table like this:
+-----------+----------+------------------------+
| week_no | ticker | ratio |
|-----------+----------+------------------------|
| 39.0 | PBRT | 0.33333333333333333333 |
| 38.0 | ADM | 0.50000000000000000000 |
| 40.0 | TSCO | 1.00000000000000000000 |
| 39.0 | AAL | 0.09090909090909090909 |
+-----------+----------+------------------------+
+-----------+------------------------+------------------------+------------------------+------------------------+
| week_no | adm | pbrt | aal | tsco |
|-----------+------------------------+------------------------+------------------------+------------------------|
| 38.0 | 0.50000000000000000000 | <null> | <null> | <null> |
| 39.0 | <null> | 0.33333333333333333333 | 0.09090909090909090909 | <null> |
| 40.0 | <null> | <null> | <null> | 1.00000000000000000000 |
+-----------+------------------------+------------------------+------------------------+------------------------+
SELECT *
FROM crosstab(
'select week_no, ticker, ratio
from rejected_ratio_per_ticker_and_week_for_crosstab
order by 1,2')
AS ct(week_no double precision, ADM numeric, PBRT numeric, AAL numeric, TSCO numeric);
+-----------+------------------------+------------------------+--------+--------+
| week_no | adm | pbrt | aal | tsco |
|-----------+------------------------+------------------------+--------+--------|
| 38.0 | 0.50000000000000000000 | <null> | <null> | <null> |
| 39.0 | 0.09090909090909090909 | 0.33333333333333333333 | <null> | <null> |
| 40.0 | 1.00000000000000000000 | <null> | <null> | <null> |
+-----------+------------------------+------------------------+--------+--------+
Answer the question
In order to leave comments, you need to log in
This is not a transformation, but the preparation of a suitable sample.
You do not change the structure of the table, only the form of obtaining data?
select t1.week_no,
(select max(t2.ratio) from table t2 where t2.week_no = t1.week_no and t2.ticker = t1.ticker and t1.ticker = 'ADM') adm,
(select max(t2.ratio) from table t2 where t2.week_no = t1.week_no and t2.ticker = t1.ticker and t1.ticker = 'PBRT') pbrt,
(select max(t2.ratio) from table t2 where t2.week_no = t1.week_no and t2.ticker = t1.ticker and t1.ticker = 'ALL') aal,
(select max(t2.ratio) from table t2 where t2.week_no = t1.week_no and t2.ticker = t1.ticker and t1.ticker = 'TSCO') tsco
from table t1
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question