使用 INNER JOIN LATERAL 和 postgresql 将宽 table 转换为长

Transform wide table to long using INNER JOIN LATERAL and postgresql

使用 postgresql,我尝试 transform/pivot 我的数据 table 1(宽格式)到新目的地 table 2 的长格式,但没有成功:

我的问题的简化示例:

Table 1

id_profil  | no_h |  P1 |   P2 |   P3 |  Pn
01              1     5      7     x1   ...
01              2     7     78     x2   ...
02              1     5      7     x3   ...

Table 2,Table 1 转换的结果:

id_profil    | no_h |  parametre   |      valeur 
01                1           P1               5
01                1           P2               7 
01                1           P3              x1 
01                2           P1               7    
01                2           P2              78    
01                2           P3              x2    
02                1           P1               5   
02                1           P2               7
02                1           P3              x3    

您可以在 this sqlfiddle 中找到并使用 table 1 structure/data。

我在一些 Whosebug 帖子中看到可以使用 INNER JOIN LATERAL 来做到这一点。 (参见 Postgres analogue to CROSS APPLY in SQL Server。)但是如何将正确的列名注入参数列?

更新

在真实的数据库中,我有150多个列,所以如果可以不在查询中手动输入每个列名,那可能会更好。

您必须对 valeur 列使用 CASE 并将其转换为常见类型(例如文本),以及参数名称列表:

with 
  table1(id_profil, no_h, parametre1, parametre2, parametre3) as (
    VALUES (01, 1, 5, 7, 'x1'::text), 
           (01, 2, 7, 78, 'x2'), 
           (02, 1, 5, 7, 'x3')
    ),
  col as (
    unnest('{parametre1,parametre2,parametre3}'::text[])
    )
select t.id_profil, t.no_h, col as parametre,
       case col when 'parametre1' then t.parametre1::text
                when 'parametre2' then t.parametre2::text
                when 'parametre3' then t.parametre3::text
       end as valeur
from col
cross join table1 t
order by 1, 2, 3