这篇文章将为大家详细讲解有关PostgreSQL行转列的方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

PostgreSQL如何行转列

方法一:group by + sum + case when

selectname,sum(casewhenzbfm='年龄'thenvalueelse0end)as年龄,sum(casewhenzbfm='身高'thenvalueelse0end)as身高,sum(casewhenzbfm='体重'thenvalueelse0end)as体重fromtestgroupbynamehavingnamelike'%1'andlength(name)=4orderby年龄desc

方法二:用postgresql的crosstab交叉函数

推荐:postgresql教程

crosstab(unknown,unknown)doesnotexistselect*fromcrosstab('selectname,zbfm,valuefromtestwherenamelike''%1''andlength(name)=4',$$values('年龄'),('身高'),('体重')$$)asscore(nametext,年龄int,身高int,体重int)orderby年龄desc

方法三:group by + string_agg + split_part(分组,行转列,字符切割)

selectname,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(selectname,string_agg(zbfm||':'||value,',')astempfromtestgroupbynamehavingnamelike'%1'andlength(name)=4)astorderby年龄desc

group by + string_agg

selectname,string_agg(zbfm||':'||value,',')fromtestgroupbynamehavingnamelike'%1'andlength(name)=4

关于PostgreSQL行转列的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。