如何创建视图

时间:2014-03-27 13:44:15

标签: oracle oracle11g

我试图创建一个视图,其中包含每个分支中最新雇用员工的信息。但我没有成功。任何人都可以指引我走向正确的道路。

    CREATE TABLE BRANCH(
    BRANCH_ID NUMBER(8) PRIMARY KEY,
    BRANCH_NAME VARCHAR2(100) NOT NULL,
    SCHEDULE_LINK_NUM NUMBER(8),
    MAIN_BRANCH_ID number(8),
    BRANCH_MGR_ID NUMBER(8),
    BRANCH_OPEN_DATE DATE,
    EMAIL VARCHAR2(50),
    URL VARCHAR2(50)
    );

    CREATE TABLE EMPLOYEE(
    EMPLOYEE_ID NUMBER(8) PRIMARY KEY,
    FIRST_NAME VARCHAR2(50),
    LAST_NAME VARCHAR2(50),
    MIDDLE_NAME VARCHAR2(50),
    GENDER CHAR(1),
    SSN NUMBER(9) NOT NULL,
    DOB DATE,
    MARITAL_STATUS VARCHAR2(30),
    SPOUSE_NAME VARCHAR2(50),
    HOME_PHONE NUMBER(10),
    CELL_PHONE NUMBER(10),
    OFFICE_PH_EXTN NUMBER(6),
    EMPLOYEE_TYPE VARCHAR2(40),
    SALARY NUMBER(10,2),
    TAX_DEDUCTION NUMBER(10,2),
    BRANCH_ID NUMBER(8),
    MGR_ID NUMBER(8),
    CONSTRAINT EMP_BRANCH_FKEY FOREIGN KEY(BRANCH_ID) REFERENCES BRANCH(BRANCH_ID),
    CONSTRAINT EMP_EMPTYPE_CHECK CHECK(EMPLOYEE_TYPE IN ('MANAGER', 'MECHANIC', 'SECRETARY', 'SALES PERSON')),
    CONSTRAINT EMP_MARITSTATUS_CHECK CHECK(MARITAL_STATUS IN ('SINGLE', 'MARRIED', 'DIVORCED'))
    );

    CREATE TABLE EMP_WORK_HISTORY(
    BRANCH_EMP_NUM NUMBER(8) PRIMARY KEY,
    BRANCH_ID NUMBER(8),
    EMPLOYEE_ID NUMBER(8),
    JOIN_DATE DATE NOT NULL,
    RELIEVING_DATE DATE,
    EMPLOYEE_TYPE VARCHAR2(40),
    DESCRIPTION VARCHAR2(200),
    CONSTRAINT BRANCH_WRKHIS_BID_FKEY FOREIGN KEY(BRANCH_ID) REFERENCES BRANCH(BRANCH_ID),
    CONSTRAINT BRANCH_WRKHIS_EID_FKEY FOREIGN KEY(EMPLOYEE_ID) REFERENCES EMPLOYEE(EMPLOYEE_ID),
    CONSTRAINT EMP_WRKHIS_EMPTYPE_CHECK CHECK(EMPLOYEE_TYPE IN ('MANAGER', 'MECHANIC', 'SECRETARY', 'SALES PERSON'))
    );

我写了如下视图:

CREATE VIEW LAST_EMPLOYEE_BRANCH AS
WITH LAST_EMP_BRANCH AS
(SELECT MAX(EWH.JOIN_DATE) AS LAST_HIRED_DATE, EWH.BRANCH_ID
 FROM EMP_WORK_HISTORY EWH GROUP BY EWH.BRANCH_ID)
SELECT E.FIRST_NAME || E.LAST_NAME AS EMPLOYEE_NAME,
B.BRANCH_NAME, LEB.LAST_HIRED_DATE, E.SALARY, 
EXTRACT(YEAR FROM NUMTOYMINTERVAL(MONTHS_BETWEEN(TRUNC(SYSDATE),E.DOB),'MONTH')) AS AGE
FROM EMPLOYEE E, BRANCH B, LAST_EMP_BRANCH LEB
WHERE E.BRANCH_ID = B.BRANCH_ID
AND LEB.BRANCH_ID = E.BRANCH_ID;

通过运行上述视图,我获得了所有员工记录。任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您似乎忘记在联接中包含EMP_WORK_HISTORY表和LAST_HIRED_DATE列。请尝试以下查询:

CREATE OR REPLACE VIEW LAST_EMPLOYEE_BRANCH AS
WITH LAST_EMP_BRANCH AS
(SELECT MAX(EWH.JOIN_DATE) AS LAST_HIRED_DATE, EWH.BRANCH_ID
 FROM EMP_WORK_HISTORY EWH GROUP BY EWH.BRANCH_ID)
SELECT E.FIRST_NAME || E.LAST_NAME AS EMPLOYEE_NAME,
B.BRANCH_NAME, LEB.LAST_HIRED_DATE, E.SALARY, 
EXTRACT(YEAR FROM NUMTOYMINTERVAL(MONTHS_BETWEEN(TRUNC(SYSDATE),E.DOB),'MONTH')) AS AGE
FROM EMPLOYEE E, BRANCH B, LAST_EMP_BRANCH LEB, EMP_WORK_HISTORY EWH
WHERE E.BRANCH_ID = B.BRANCH_ID
AND LEB.BRANCH_ID = E.BRANCH_ID
AND E.EMPLOYEE_ID = EWH.EMPLOYEE_ID
AND B.BRANCH_ID = EWH.BRANCH_ID
AND LEB.LAST_HIRED_DATE = EWH.JOIN_DATE;