我有一个名为fund_flag的表,它包含FundTYPE、Fund1、Fund2、Fund3、Fund4、Fund5、Fund6、Sign_Val等列

表格数据如下所示.

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 -

我希望输出如下:

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

请帮我回答这个问题.

推荐答案

在Oracle或SQL Server中,这可以使用UNPIVOT操作符实现,但在Postgres中不可用.但是,您可以使用VALUES()JOIN LATERAL来取消透视列:

select f.fund_type, t.*, f.sign_val
from fund_flag f
  cross join lateral (
     values 
       (f.fund1, 'fund1'),
       (f.fund2, 'fund2'),
       (f.fund3, 'fund3'),
       (f.fund4, 'fund4'),
       (f.fund5, 'fund5'),
       (f.fund6, 'fund6')
  ) as t(fund_name, fund_value)
order by fund_type;

Demo here

Postgresql相关问答推荐

用于JSON数组的带有组合条件的Postgres JSONB Select 查询

PostgreSQL(container)中使用80K子分区表处理共享内存不足错误

Jsonb[]字段中的PostgreSQL否定&q;-0.0

是否从表中 Select 值?巴什

sqlalchemy在Flask 下运行时出现无法解释的错误

将具有自定义类型的表从一种模式复制到另一种模式

Postgres 14 反斜杠 Z 没有给出正确的输出

PostgreSQL - 继承表的常见自动增量

使用 Heroku CLI、Postgres 的 SQL 语法错误

使用 JDBC 连接到 PostgreSql 的本地实例

如何在 Sequelize ORM 中插入 PostGIS GEOMETRY 点?

全文搜索(Postgres)与Elastic search

Postgresql JSONB 来了.现在用什么?Hstore?JSON?EAV?

使用 ON CONFLICT 从 INSERT 返回行,无需更新

如何将 postgres 数据库转换为 sqlite

什么是 postgres 超级用户

我如何知道我的 PostgreSQL 服务器是否使用C语言环境?

丢弃顺序和级联

在 PostgreSQL 中显示正在运行的查询的全文

为 postgresql 存储过程设置隔离级别