PostgreSql如何实现行转列

博客介绍了三种方法,并分别给出了相应结果,但未详细说明方法内容。整体围绕方法及结果展开,与信息技术相关,可能涉及 Java 编程等方面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

表格如下:
测试表格

1. 方法一:

select pname,
sum(case when project = '身高' then tvalue else 0 end )as 身高 ,
String_agg(case when project = '身高' then unit else null end,'')as 身高单位 ,
sum(case when project = '体重' then tvalue else 0 end )as 体重 ,
String_agg(case when project = '体重' then unit else null end,'')as 体重单位 ,
sum(case when project = '年龄' then tvalue else 0 end )as 年龄 ,
String_agg(case when project = '年龄' then unit else null end,'')as 年龄单位
from healthexamination group by pname
order by 年龄 desc;

结果如下:
方法一结果

方法二:

select pname,String_agg(project||':'||tvalue||unit,',') from healthexamination group by pname;

结果如下:
方法二结果

方法三:

select pname,
split_part(split_part(temp,',',1),':',2)as 身高,
split_part(split_part(temp,',',1),':',3)as 身高单位,
split_part(split_part(temp,',',2),':',2)as 体重,
split_part(split_part(temp,',',2),':',3)as 体重单位,
split_part(split_part(temp,',',3),':',2)as 年龄,
split_part(split_part(temp,',',3),':',3)as 年龄单位
from(
select pname,String_agg(project||':'||tvalue||':'||unit,',')as temp from healthexamination group by pname)as t order by 年龄 desc; 

结果如下
方法三结果

### PostgreSQL行转列和列转行的操作 #### 行转列 (Pivot) 在 PostgreSQL 中,`crosstab()` 函数用于执行行转列操作。此函数位于 `tablefunc` 扩展中,在使用前需确认已启用该扩展。 为了展示如何进行行转列,假设有一个名为 `sales` 的表格: | year | product | sales | |------|---------|-------| | 2021 | A | 10 | | 2021 | B | 15 | | 2022 | A | 20 | | 2022 | B | 25 | 目标是将产品列为单独的一列,并按年份汇总销售量。以下是具体实现方式: ```sql CREATE EXTENSION IF NOT EXISTS tablefunc; SELECT * FROM crosstab( 'SELECT year, product, sales FROM sales ORDER BY 1' ) AS ct(year int, "A" int, "B" int); ``` 这段 SQL 将返回如下结果[^4]: | year | A | B | |------|----|----| | 2021 | 10 | 15 | | 2022 | 20 | 25 | #### 列转行 (Unpivot) 对于列转行的需求,则可以通过标准的 SQL 查询来完成这一转换过程。给定一张宽表形式的数据集,比如下面这张包含多个指标的表格: | id | metric_1 | metric_2 | |--| | 1 | 100 | 200 | | 2 | 150 | 250 | 要将其转化为长表结构,可采用以下查询语句: ```sql SELECT id, unnest(array['metric_1', 'metric_2']) as metrics, unnest(array[metric_1::text, metric_2::text])::int as values FROM wide_table; ``` 上述命令的结果将是这样的格式[^2]: | id | metrics | values | |-----|----------|--------| | 1 | metric_1 | 100 | | 1 | metric_2 | 200 | | 2 | metric_1 | 150 | | 2 | metric_2 | 250 | 通过这种方式可以在不需要额外插件的情况下轻松地实施 Unpivot 操作
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值