PostgreSQL行转列的多种方法
作者:围城客
这篇文章主要介绍了PostgreSQL行转列的多种方法,本文给大家分享三种方法,每种方法结合示例代码给大家介绍的非常详细,需要的朋友可以参考下
PostgreSQL如何行转列
方法一:group by + sum + case when
select name, sum(case when zbfm='年龄' then value else 0 end) as 年龄, sum(case when zbfm='身高' then value else 0 end) as 身高, sum(case when zbfm='体重' then value else 0 end) as 体重 from test group by name having name like '%1' and length(name)=4 order by 年龄 desc
方法二:用postgresql的crosstab交叉函数
crosstab(unknown, unknown) does not exist select * from crosstab( 'select name,zbfm,value from test where name like ''%1'' and length(name)=4',$$values('年龄'), ('身高'), ('体重')$$) as score(name text, 年龄 int, 身高 int, 体重 int) order by 年龄 desc
方法三:group by + string_agg + split_part(分组,行转列,字符切割)
select name, split_part(split_part(temp,',',1),':',2) as 年龄, split_part(split_part(temp,',',2),':',2) as 身高, split_part(split_part(temp,',',3),':',2) as 体重 from( select name, string_agg(zbfm||':'||value,',') as temp from test group by name having name like '%1' and length(name)=4 ) as t order by 年龄 desc
group by + string_agg
select name, string_agg(zbfm||':'||value,',') from test group by name having name like '%1' and length(name)=4
到此这篇关于PostgreSQL如何行转列的文章就介绍到这了,更多相关PostgreSQL行转列内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!