• 技术文章 >数据库 >PostgreSQL

    PostgreSQL如何行转列

    月亮邮递员月亮邮递员2020-03-28 16:29:46原创5822

    PostgreSQL如何行转列

    方法一:group by + sum + case when

    1

    2

    3

    4

    5

    6

    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

    1046062-20180825235958854-1973325843.png

    1046062-20180825232833796-1765452126.png

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

    推荐:postgresql教程

    1

    2

    3

    4

    5

    6

    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

    1046062-20180825233903502-1086057566.png

    1046062-20180825233124084-718406010.png

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    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

    1046062-20180825234240202-1361501403.png

    1046062-20180825234118721-1133248578.png

    group by + string_agg

    1

    2

    3

    select name, string_agg(zbfm||':'||value,',') from test

    group by name

    having name like '%1' and length(name)=4

    1046062-20180825234344420-1654565508.png

    更多技术请关注Python视频教程

    专题推荐:postgresql 行转列
    上一篇:PostgreSQL数组类型怎么定义 下一篇:PostgreSQL如何更改数据类型

    相关文章推荐

    • PostgreSQL怎么导出表结构• PostgreSQL怎么查询数据库• PostgreSQL远程不能连接数据库怎么办• PostgreSQL数组类型怎么定义

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网