I have a table called fund_flag and it has columns like fund_type, fund1, fund2, fund3, fund4, fund5, fund6, sign_val
and table data is as follows.
fund_type | fund1 | fund2 | fund3 | fund4 | fund5 | fund6 | sign_val |
---|---|---|---|---|---|---|---|
SGP | Y | N | N | N | Y | N | – |
USD | Y | N | Y | Y | Y | N | + |
INR | N | N | Y | N | Y | Y | – |
I want output like :
fund_type | fund_name | fund_value | sign_val |
---|---|---|---|
SGP | fund1 | Y | – |
SGP | fund2 | N | – |
SGP | fund3 | N | – |
SGP | fund4 | N | – |
SGP | fund5 | Y | – |
SGP | fund6 | N | – |
USD | fund1 | Y | + |
USD | fund2 | N | + |
USD | fund3 | Y | + |
USD | fund4 | Y | + |
USD | fund5 | Y | + |
USD | fund6 | N | + |
in the same way for INR |
Please help me with the query.
2
Answers
In Oracle or SQL Server this could be achieved with the UNPIVOT operator, but that is not available in Postgres. However You could use
VALUES()
andJOIN LATERAL
to unpivot the columns :Demo here