SQL:“反向”转置表

时间:2017-06-01 07:36:50

标签: sql postgresql unpivot

我从下表中看到了很多关于转置的问题......

scanid | region | volume
-------------------------
1          A      34.4
1          B      32.1
1          C      29.1
2          A      32.4
2          B      33.2
2          C      35.6

到这张桌子。

scanid | A_volume | B_volume | C_volume
----------------------------------------
1        34.4         32.1      29.1
2        32.4         33.2      35.6

然而,我需要做反过来,并且无法试图解决这个问题。有人可以帮忙吗?

谢谢。

2 个答案:

答案 0 :(得分:2)

目前尚不清楚如何恢复" A"," B"," C"值,所以我只是添加它们

制备

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)

选择

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)

来自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)

答案 1 :(得分:1)

您可以使用UNION子句非常简单地执行此操作:

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