使用INNER JOIN LATERAL和postgresql将宽表转换为long

时间:2016-06-27 08:42:09

标签: sql database postgresql pivot inner-join

使用postgresql,我尝试将表1(宽格式)中的数据转换/转换为长格式的新目标表2,但没有成功:

我的问题的简化示例:

表1

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

表2,表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中找到并使用表1结构/数据。

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

更新

在真实数据库中,我有超过150列,所以如果可能无法在查询中手动输入每个列名,那么它可能会更好。

1 个答案:

答案 0 :(得分:1)

您必须为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