1

I have a table that has rows that look like this

Account Currency Amount
1 USD 5
1 EUR 10
2 USD 8
3 EUR 4

Is there a way to do a select query so it would return something like

Account amount_usd amount_eur
1 5 10
2 8
3 4

usd and eur are hardcoded, so i dont have to build the name from the column.

suppandi g
  • 504
  • 1
  • 5
  • 18
  • This is well explained in this question: https://stackoverflow.com/questions/23060256/postgres-transpose-rows-to-columns – rodolfo_r Mar 01 '21 at 20:00
  • 2
    Does this answer your question? [Postgres - Transpose Rows to Columns](https://stackoverflow.com/questions/23060256/postgres-transpose-rows-to-columns) – astentx Mar 01 '21 at 21:16

2 Answers2

1

You can use conditional aggregation which in Postgres uses filter:

select account,
       sum(amount) filter (where currency = 'USD') as usd_amount,
       sum(amount) filter (where currency = 'EUR') as eur_amount
from t
group by account;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

You can use sum() with case when condition :

select account, sum(case when currency='USD' then amount end) Amount_USD,
sum(case when currency='EUR' then amount end) Amount_EUR
from myTable
Group by account