Asnim P Ansari
Asnim P Ansari

Reputation: 2477

Transform row wise postgres data to grouped column wise data

I have a stock market data which looks likes like

instrument_symbol|close |timestamp          |
-----------------|------|-------------------|
IOC              |134.15|2019-08-05 00:00:00|
YESBANK          | 83.75|2019-08-05 00:00:00|
IOC              |135.25|2019-08-02 00:00:00|
YESBANK          |  88.3|2019-08-02 00:00:00|
IOC              |136.95|2019-08-01 00:00:00|
YESBANK          |  88.4|2019-08-01 00:00:00|
IOC              | 139.3|2019-07-31 00:00:00|
YESBANK          |  91.2|2019-07-31 00:00:00|
YESBANK          | 86.05|2019-07-30 00:00:00|
IOC              | 133.5|2019-07-30 00:00:00|
IOC              |138.25|2019-07-29 00:00:00|

I want to transform it to

timestamp,           IOC,     YESBANK
2019-08-05 00:00:00  134.15   83.75
2019-08-02 00:00:00  135.25   88.3
......
.....
...


format.

Is there some Postgres query to do this? Or do we have to do this programmatically?

Upvotes: 0

Views: 344

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269493

You can use conditional aggregation. In Postgres, I like the filter syntax:

select "timestamp",
       max(close) filter (where instrument_symbol = 'IOC') as ioc,
       max(close) filter (where instrument_symbol = 'YESBANK') as yesbank
from t
group by "timestamp"
order by 1 desc;

Upvotes: 2

Kaushik Nayak
Kaushik Nayak

Reputation: 31648

Use conditional aggregation.

select "timestamp" :: date, max( case 
                         when instrument_symbol = 'IOC' 
                        then close end ) as ioc,
                   max( case 
                         when instrument_symbol = 'YESBANK' 
                        then close end ) as yesbank FROM t
                        group by "timestamp" :: date
                        order by 1 desc

DEMO

Upvotes: 1

Related Questions