根据多个列值拆分一行

Split a row based on multiple column values

我在 postgres 中关注 table(下面仅显示 2 行)。

trial_id    lead_sponsor    lead_sponsor_class  collaborators   collaborators_class 
NCT00004336 NCRR    NIH University of Michigan  Other
NCT00004337 NCRR    NIH null    null

我想根据列 lead_sponsor 和协作者拆分每一行,并根据它们创建新列

预期输出为:

trial_id    sponsor_company           sponsor_role        agency
NCT00004336 NCRR                      lead_sponsor        NCRR
NCT00004336 University of Michigan    collaborators       University of Michigan
NCT00004337 NCRR                      lead_sponsor        NCRR

我尝试了一些方法,但我无法找出解决方案(我是 postgres 的新手)

SELECT
    *,
    CASE WHEN lead_sponsor is not null THEN lead_sponsor
         WHEN collaborators is not null THEN collaborators
         ELSE ''
    END AS sponsor_company
FROM
    tb ;

这里的任何建议都会很有帮助。

谢谢

您可以使用横向联接取消透视:

select x.*
from mytable t
cross join lateral (values 
    (trial_id, lead_sponsor,  'lead_sponsor', lead_sponsor),
    (trial_id, collaborators, 'collaborators', collaborators)
) x(trial_id, sponsor_company, sponsor_role, agency)
where x.sponsor_company is not null

Demo on DB Fiddle:

trial_id    | sponsor_company | sponsor_role  | agency    
:---------- | :-------------- | :------------ | :---------
NCT00004336 | NCRR            | lead_sponsor  | NCRR      
NCT00004336 | University      | collaborators | University
NCT00004337 | NCRR            | lead_sponsor  | NCRR