就业数据 - Pivot table,将所有就业数据放在一行中

employment data - Pivot table, placing all employment data in one row

你好,我 table 如下

employee id job start_dt
1 abc 1/1/2021
1 def 5/1/2021
2 xyz 6/1/2021
2 rfd 8/1/2021
2 hgf 7/1/2021
2 esd 1/1/1999

我想知道是否有一种方法可以旋转 table 并将所有工作和日期放在同一行,

employee id job_a start_dt_ a job_b start_dt_b job_c start_dt_c job_d start_dt_d job_e start_dt_e job_f start_dt_f
1 abc 1/1/2021 def 5/1/2021
2 xyz 6/1/2021 rfd 8/1/2021 hgf 7/1/2021 esd 1/1/1999

(table 姓名 'JOB')

您可以使用条件聚合以及ROW_NUMBER()分析函数,例如

WITH j AS
(  
 SELECT ROW_NUMBER() OVER (PARTITION BY employee_id ORDER BY start_dt) AS rn,
        j.*
   FROM job j
)
SELECT employee_id, 
       MAX(CASE WHEN rn = 1 THEN job END) AS job_a,
       MAX(CASE WHEN rn = 1 THEN start_dt END) AS start_dt_a,  
       MAX(CASE WHEN rn = 2 THEN job END) AS job_b,
       MAX(CASE WHEN rn = 2 THEN start_dt END) AS start_dt_b,
       MAX(CASE WHEN rn = 3 THEN job END) AS job_c,
       MAX(CASE WHEN rn = 3 THEN start_dt END) AS start_dt_c,
       MAX(CASE WHEN rn = 4 THEN job END) AS job_d,
       MAX(CASE WHEN rn = 4 THEN start_dt END) AS start_dt_d              
  FROM j
 GROUP BY employee_id
 ORDER BY employee_id 

Demo

P.S。 当前结果集排序逻辑不够清晰