Search code examples
sqlpostgresqlpivotcrosstab

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?


Solution

  • 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;