1、说明
行列转换是数据库查询中比较常见的一种需求,在Greenplum这种偏向OLAP场景的数据库中更是比较常见了。那么我们如何在gp中实现行列转换呢?我们可以使用postgresql的tablefunc扩展在gp中来直接实现行列转换的功能。
不过在gp中并不像postgresql那样自带tablefunc扩展,因此我们需要将postgresql中的该扩展解压到gp中来使用。
2、安装
安装前要先根据greenplum的版本选择对应的postgresql版本,例如这里我使用的gp5.23版本,所以这里要先下载postgresql8.3.23的源码包来使用。
很可惜的是,postgresql官网目前能够下载的最旧的版本是pg9.5,这里我是在这个网站下载的源码包:
https://ftp.postgresql.org/pub/source/
下载完之后进行解压安装:
gpadmin用户:
cd postgresql-8.3.23/contrib/tablefunc
make USE_PGXS=1 install
然后将tablefunc.so发送到gpdb其他机器上:
gpscp -f seg_hosts /usr/local/greenplum-db-5.23.0/lib/postgresql/tablefunc.so =: /usr/local/greenplum-db-5.23.0/lib/postgresql/
执行tablefunc.sql脚本安装该扩展:
psql bill bill -f /usr/local/greenplum-db-5.23.0/share/postgresql/contrib/tablefunc.sql
安装完成:
3、使用
tablefunc用法:
PostgreSQL tablefunc详解(兼容oracle connect by)
PostgreSQL行列转换(兼容oracle pivot unpivot)
参考链接:
http://www.postgres.cn/docs/12/tablefunc.html