How to unpivot a table in PostgreSQL

前端 未结 4 781
野趣味
野趣味 2020-12-07 03:39

I am having difficulties writing a Postgres function, as I am not familiar with it. I have multiple tables to import into Postgres with this format:

id | 196         


        
4条回答
  •  清歌不尽
    2020-12-07 04:22

    The simplest way is a union all:

    select id, 1960 as year, "1960" as value
    from table t
    union all
    select id, '1960', "1961"
    from table t
    . . .;
    

    A somewhat more sophisticated way would be:

    select t.id, s.yr,
           (case when s.yr = 1960 then "1960"
                 when s.yr = 1961 then "1961"
                 . . .
            end) as value
    from table t cross join
         generate_series(1960, 1980) s(yr);
    

    You can put this into another table using insert or create table as.

提交回复
热议问题