如何从 table 中获取字段列表和不同的值

How to get a list of fields and distinct values from a table

我需要将列反转为行,然后将不同的值放在一起。理想情况下使用 postgresql,但如果解决方案更容易,可以使用 python。还需要是动态的,因为每次转换 运行 时字段都会变化。我已经搜索过,但很难找到与此类似的内容。

源数据table:

option1 option2 option3
1 A X
1 B Y
2 A X
3 B Y
3 A X

目标 table:

fieldname option
option1 1
option1 2
option1 3
option2 A
option2 B
option3 X
option3 Y

有两种方法可以做到这一点

  1. 使用UNNEST
select distinct 
unnest(array['option1','option2','option3']),
unnest(array[option1,option2,option3])
from test
order by 1,2
  1. 使用Cross Join Lateral
select distinct t2.*
from test t1
  cross join lateral (
     values 
       ('option1',t1.option1 ),
       ('option2',t1.option2),
       ('option3',t1.option3)
       
  ) as t2(option, value)
order by 1,2

DEMO