I have this query in Postgres:
Select
"Charges"."saleAmount", "Charges"."buyAmount", "Operations"."id"
From
"Charges"
Left Join
"Operations" On "Operations"."id" = "Charges"."operationsId"
Order By
"Operations"."id"
saleAmount | buyAmount | id |
---|---|---|
200 | NULL | id1 |
300 | 500 | id2 |
0 | 100 | id3 |
I need to transform it: Add a new column type
depending on saleAmount
> 0 or buyAmount
> 0, and separate into two rows when I have both saleAmount
and buyAmount
in the same row.
saleAmount | buyAmount | id | type |
---|---|---|---|
200 | NULL | id1 | sale |
300 | 0 | id2 | sale |
0 | 500 | id2 | buy |
0 | 100 | id3 | buy |
How do I transform my table into this format?
Column type
can be made with:
(CASE
WHEN "saleAmount" > 0 THEN 'sale'
WHEN "buyAmount" > 0 THEN 'buy'
END) as "type"
4
Answers
You can join to a values table constructor and use a case expression to determine how many rows qualify for the join:
I think you can use union all.
You can use
UNION ALL
to create two rows out of one. E.g.:The join of the Operations table seems superfluous by the way. Either the Charges has an operationsId, then it links to an Operations row with the same ID or it doesn’t have an operationsId, then it doesn’t link to Operations row. So why not just show the "Charges"."operationsId" instead of joining to the Operations table just to show the same ID?
In Postgres you can unpivot the two columns to rows with
values
and a lateral join, then filter out unwanted rows in thewhere
clause:It is not obvious what the purpose of the
left join
in the original query is, so I left it apart – but you can easily add it to the query if needed.