使用内部连接的横向和后Ql将宽表转换为长期



使用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    

您可以在此sqlfiddle中找到并使用表1的结构/数据。

我在一些Stackoverflow帖子中看到,可以使用INNER JOIN LATERAL来做到这一点。(请参阅SQL Server中的Postgres类似物。)但是如何将正确的列名注入参数列?

update

在实际数据库中,我有150列以上,因此,如果可以在查询中不手动输入每个列名,则可能更好。

您必须使用valeur列的案例,然后将其施放为公共类型(例如文本),以及参数名称的列表:

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

最新更新