ROW中每个人的最后3个就业信息

时间:2019-07-19 14:21:16

标签: sql oracle top-n

我需要连续显示每个人的最后三个雇主名称。

我使用了Rank()和Max()方法,并且想知道是否存在使用分析函数解决此问题的简便方法。我尝试使用NTH_VALUE,但仍需要max函数以行格式显示结果。

SELECT 
ID,
MAX(CASE WHEN RANK=1 THEN EMPLOYER_NAME END) EMPLOYER_NAME1,
MAX(CASE WHEN RANK=2 THEN EMPLOYER_NAME END) EMPLOYER_NAME2,
MAX(CASE WHEN RANK=3 THEN EMPLOYER_NAME END) EMPLOYER_NAME3

FROM (
SELECT ID,EMPLOYER_NAME,RANK() OVER (PARTITION BY ID ORDER BY START_DATE DESC) RANK
FROM EMP
)

WHERE RANK<4
GROUP BY ID

所需的输出:

ID,  EMPLOYER_NAME1, EMPLOYER_NAME2, EMPLOYER_NAME3
max, delotte       , apple,          google

1 个答案:

答案 0 :(得分:1)

您需要一个GROUP BY

SELECT ID,
       MAX(CASE WHEN RANK = 1 THEN EMPLOYER_NAME END) as EMPLOYER_NAME1,
       MAX(CASE WHEN RANK = 2 THEN EMPLOYER_NAME END) as EMPLOYER_NAME2,
       MAX(CASE WHEN RANK = 3 THEN EMPLOYER_NAME END) as EMPLOYER_NAME3    
FROM (SELECT ID,EMPLOYER_NAME,RANK() OVER (PARTITION BY ID ORDER BY START_DATE DESC) RANK
      FROM EMP
    ) e
WHERE RANK < 4
GROUP BY id;

请注意,ELSE NULL是不必要的,因为这是CASE表达式在没有ELSE的情况下的工作方式。