请在数据下方
Emp. Date. Dept
1. 01/21. Abc
1. 02/15. Xyz
1. 10/19. Cba
2. 01/21. Abc
2. 02/15. Xyz
2. 04. Uvw
使用Oracl Sql,如果在部门工作超过6个月的员工让该部门成为当前部门,则我需要在一年中为每个雇员提取
上述数据的预期结果
Emp. Dept
1. Xyz. (Emp workes more than 6 months)
2. Uvw. (No department with 6 months tenure so current department)
答案 0 :(得分:0)
您可以使用以下内容:
我已经根据示例创建了表和数据。
-- Preparing the data
CREATE TABLE EMPLOYEES (
EMP NUMBER,
DATE1 DATE,
DEPT VARCHAR2(100)
);
INSERT INTO EMPLOYEES VALUES (
1,
TO_DATE('01/21', 'MM/DD'),
'Abc'
);
INSERT INTO EMPLOYEES VALUES (
1,
TO_DATE('02/15', 'MM/DD'),
'Xyz'
);
INSERT INTO EMPLOYEES VALUES (
1,
TO_DATE('10/19', 'MM/DD'),
'Cba'
);
INSERT INTO EMPLOYEES VALUES (
2,
TO_DATE('01/21', 'MM/DD'),
'Abc'
);
INSERT INTO EMPLOYEES VALUES (
2,
TO_DATE('02/15', 'MM/DD'),
'Xyz'
);
INSERT INTO EMPLOYEES VALUES (
2,
TO_DATE('04', 'MM'),
'Uvw'
);
-
-- Final data in the table
SELECT
*
FROM
EMPLOYEES;
-- Your Query
SELECT
EMP,
DEPT
FROM
(
SELECT
EMP,
DEPT,
ROW_NUMBER() OVER(
PARTITION BY EMP
ORDER BY
DURATION DESC NULLS LAST
) AS RN
FROM
(
SELECT
EMP,
DATE1,
DEPT,
MONTHS_BETWEEN(LEAD(DATE1, 1) OVER(
PARTITION BY EMP
ORDER BY
DATE1
), DATE1) AS DURATION
FROM
EMPLOYEES
)
WHERE
DURATION >= 6
OR DURATION IS NULL
)
WHERE
RN = 1;
输出:
希望,这对您有用。
干杯!