我有以下数据,需要以下快速帮助。(提供EMP表示例,由于合规性问题我无法提供真实数据):
SELECT EMPNO,
JOB,
HIREDATE,
HIREDATE AS STARTDATE,
LEAD(HIREDATE) OVER (ORDER BY HIREDATE) AS ENDDATE
FROM SCOTT.EMP
ORDER BY HIREDATE;
EMPNO JOB HIREDATE STARTDATE ENDDATE
--------------------------------------------------
7369 CLERK 17-Dec-80 17-Dec-80 20-Feb-81
7499 SALESMAN 20-Feb-81 20-Feb-81 22-Feb-81
7521 SALESMAN 22-Feb-81 22-Feb-81 2-Apr-81
7566 MANAGER 2-Apr-81 2-Apr-81 1-May-81
7698 MANAGER 1-May-81 1-May-81 9-Jun-81
7782 MANAGER 9-Jun-81 9-Jun-81 8-Sep-81
7844 SALESMAN 8-Sep-81 8-Sep-81 28-Sep-81
7654 SALESMAN 28-Sep-81 28-Sep-81 17-Nov-81
7839 PRESIDENT 17-Nov-81 17-Nov-81 3-Dec-81
7900 CLERK 3-Dec-81 3-Dec-81 3-Dec-81
7902 ANALYST 3-Dec-81 3-Dec-81 23-Jan-82
7934 CLERK 23-Jan-82 23-Jan-82 19-Apr-87
7788 ANALYST 19-Apr-87 19-Apr-87 23-May-87
7876 CLERK 23-May-87 23-May-87 NULL
这里我想在oracle SQL中按作业分区,这样连续的行获得相同的派生开始日期(DERSTARTDATE)和派生结束日期(DERENDDATE),如下所示。您能否在Oracle中使用SQL提供建议。
我想要这样的事情:
EMPNO JOB HIREDATE DERSTARTDATE DERENDDATE
-----------------------------------------------------
7369 CLERK 17-Dec-80 17-Dec-80 20-Feb-81
7499 SALESMAN 20-Feb-81 20-Feb-81 2-Apr-81
7521 SALESMAN 22-Feb-81 20-Feb-81 2-Apr-81
7566 MANAGER 2-Apr-81 2-Apr-81 8-Sep-81
7698 MANAGER 1-May-81 2-Apr-81 8-Sep-81
7782 MANAGER 9-Jun-81 2-Apr-81 8-Sep-81
7844 SALESMAN 8-Sep-81 8-Sep-81 17-Nov-81
7654 SALESMAN 28-Sep-81 8-Sep-81 17-Nov-81
7839 PRESIDENT 17-Nov-81 17-Nov-81 3-Dec-81
7900 CLERK 3-Dec-81 3-Dec-81 3-Dec-81
7902 ANALYST 3-Dec-81 3-Dec-81 23-Jan-82
7934 CLERK 23-Jan-82 23-Jan-82 19-Apr-87
7788 ANALYST 19-Apr-87 19-Apr-87 23-May-87
7876 CLERK 23-May-87 23-May-87 NULL
我的要求是如果连续重复相同的工作,例如对于Salesman,startdate和enddate应该是startdate的min和所有连续列中enddate的最大值。
示例:
答案 0 :(得分:0)
首先需要识别相同连续作业的组。 Tabibitosan是一种简单的方法。
select empno, job, hiredate,
lead(hiredate) over (order by hiredate,empno) startdate,
row_number() over (order by hiredate,empno) -
row_number() over (order by job, hiredate,empno) grp
from emp
);
识别出组后,可以使用MIN / MAX作为分析函数,并在每组中找到MIN / MAX。
with x as (
select empno, job, hiredate,
lead(hiredate) over (order by hiredate,empno) startdate,
row_number() over (order by hiredate,empno) -
row_number() over (order by job, hiredate,empno) grp
from emp
)
select empno, job, hiredate,
min(hiredate) over (partition by grp) derstartdate,
max(startdate) over (partition by grp) derenddate
from x
order by hiredate;