这篇文章将为大家详细讲解有关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交叉函数
推荐:postgresql教程
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行转列的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。