Convert one row into multiple rows with fewer columns

后端 未结 3 1964
小鲜肉
小鲜肉 2020-12-12 04:44

I\'d like to convert single rows into multiple rows in PostgreSQL, where some of the columns are removed. Here\'s an example of the current output:

name | st         


        
3条回答
  •  伪装坚强ぢ
    2020-12-12 05:36

    One way:

    with times(name , st , ot , dt) as(
    select 'Fred',8  , 2  , 3  union all
    select 'Jane',8  , 1  , 0  union all
    select 'Samm',8  , 0  , 6  union all
    select 'Alex',8  , 0  , 0  
    )
    
    select name, key as t, value::int  from 
    (
        select name, json_build_object('st' ,st , 'ot',ot, 'dt',dt) as j
        from times
    ) t
    join lateral json_each_text(j)
    on true
    where value <> '0'
    -- order by name, case when key = 'st' then 0 when key = 'ot' then 1 when key = 'dt' then 2 end
    

提交回复
热议问题