PostgreSQL行转列

管理拓展

启用拓展

-- 启用拓展
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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值