使用 SQL 将宽格式数据转换为长格式

Convert wide format data to long format using SQL

我最近开始使用 SQL 进行数据处理。所以,如果这太基础了,请原谅我。 我有以下格式的数据 table1。

id  pg_a  pg_b
12   1     0
35   1     1
46   0     1

我想将其转换成如下所示的长格式 table。

id  pg  value
12  a     1
12  b     0
35  a     1
35  b     1
46  a     0
46  a     1

我有一个 sql 使用 case when 的查询,但是没有成功。在两个 case 语句中,查询只执行第一个 when。

这是查询:

select id,
(case when pg_a is not null then pg_a
     when pg_b is not null then pg_b
     else null 
 end) AS pg,
(case when pg_a is not null then a
      when pg_b is not null then b
      else null
 end) AS value
from table1

我需要做哪些不同的事情?任何指针将不胜感激。

提前致谢。

您可以使用横向连接:

select t.id, v.*
from t cross join lateral
     (values ('a', pg_a), ('b', pg_b)
     ) v(pg, value);

如果您是 SQL 的新手,您可能更习惯 union all:

select id, 'a' as pg, pg_a as value
from t
union all
select id, 'b', pg_b
from t;