SQL: “Reverse” transpose a table

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-02 07:13:52

You could do this very simply with a UNION clause:

Select Scan_ID, 'A' as Region, A_Volume as volume
    union all
Select Scan_ID, 'B' as Region, B_Volume as volume
    union all
Select Scan_ID, 'C' as Region, C_Volume as volume

it is not clear how you restore "A", "B", "C" values, so I just add them

prepare:

t=# create table s188 (scanid int,a float, b float,c float);
CREATE TABLE
t=# insert into s188 select 1,2,3,4;
INSERT 0 1
t=# insert into s188 select 2,12,13,14;
INSERT 0 1
t=# select * from s188;
 scanid | a  | b  | c
--------+----+----+----
      1 |  2 |  3 |  4
      2 | 12 | 13 | 14
(2 rows)

select:

t=# with a as (
  select scanid,unnest(array[a,b,c]) from s188
)
select scanid,chr((row_number() over (partition by scanid))::int + 64),unnest
from a;
 scanid | chr | unnest
--------+-----+--------
      1 | A   |      2
      1 | B   |      3
      1 | C   |      4
      2 | A   |     12
      2 | B   |     13
      2 | C   |     14
(6 rows)

and more neat solution from a_horse_with_no_name

t=# with a as (
  select scanid, x.*
  from s188, unnest(array[a,b,c]) with ordinality as x(volume,idx)
)
select scanid,
       chr(idx::int + 64) as region,
       volume
from a;
 scanid | region | volume
--------+--------+--------
      1 | A      |      2
      1 | B      |      3
      1 | C      |      4
      2 | A      |     12
      2 | B      |     13
      2 | C      |     14
(6 rows)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!