管理拓展
启用拓展
-- 启用拓展
create extension tablefunc; --tablefunc扩展模块包含一系列返回记录表的函数。
create extension "uuid-ossp";--uuid扩展函数
拓展启动后,可以在public
空间下查看到crosstab函数
卸载函数
drop extension tablefunc;
drop extension "uuid-ossp";
查看拓展
\dx
行转列
创建测试表tmp_lxf_cth
,并插入数据
-- ----------------------------
-- Table structure for tmp_lxf_cth
-- ----------------------------
DROP TABLE IF EXISTS "tmp_lxf_cth";
CREATE TABLE "tmp_lxf_cth" (
"id" int4 NOT NULL
"rowid" text NOT NULL,
"rowdt" timestamp(6),
"attr" text,
"val" text
);
-- ----------------------------
-- Records of tmp_lxf_cth
-- ----------------------------
INSERT INTO "tmp_lxf_cth" VALUES (1,'t1', '2023-06-11 09:50:36', 'temp', '11', );
INSERT INTO "tmp_lxf_cth" VALUES (2,'t1', '2023-06-12 09:51:00', 'volt', '12', );
INSERT INTO "tmp_lxf_cth" VALUES (3,'t2', '2023-06-21 09:50:36', 'temp', '21', );
INSERT INTO "tmp_lxf_cth" VALUES (4,'t2', '2023-06-22 09:50:36', 'volt', '22', );
-- ----------------------------
-- Primary Key structure for table tmp_lxf_cth
-- ----------------------------
ALTER TABLE "tmp_lxf_cth" ADD CONSTRAINT "tmp_lxf_cth_pkey" PRIMARY KEY ("id");
表内容
查询结果
select distinct attr from tmp_lxf_cth order by 1;
行转列
select *
from crosstab
(
-- 要转换的数据
'SELECT rowid,rowdt,attr,val FROM tmp_lxf_cth order by 1',
-- 属性列表
'select distinct attr from tmp_lxf_cth order by 1'
)
as(
-- 最终显示列名
rowid text,
rowdt "timestamp",
temp int4,
volt int4
)
参考:https://blog.csdn.net/qq_31156277/article/details/90598311