Join two tables date from first in range of dates from second

前端 未结 3 1289
离开以前
离开以前 2021-01-19 19:18

I have two tables like below (date format: yyyy-MM-dd):
1) Table1 - EMPLOYEE_OVERTIMES (alias: EO)

EMPLOYEE_ID | OVERTIME_DATE
--------------------         


        
相关标签:
3条回答
  • 2021-01-19 19:29

    You can use simple INNER JOIN

    ;WITH EO AS 
    (
        SELECT 1 AS EID, '2012-04-01' AS OD
        UNION ALL
        SELECT 2, '2012-08-14'
        UNION ALL
        SELECT 3, '2012-07-22'
        UNION ALL
        SELECT 4, '2012-10-30'
        UNION ALL
        SELECT 5, '2012-06-07'
    ), EH AS
    (
        SELECT 1 AS EID, '2012-03-28' AS SD, '2012-04-10' AS ED
        UNION ALL
        SELECT 2, '2012-01-14', '2012-01-30'
        UNION ALL
        SELECT 3, '2012-07-15', '2012-07-25'
        UNION ALL
        SELECT 4, '2012-10-10', '2012-10-13'
        UNION ALL
        SELECT 5, '2012-06-01', '2012-06-07'
    )
    
    SELECT EH.EID, EH.SD, EH.ED, EO.OD 
    FROM EO
    INNER JOIN EH
        ON EH.SD <= EO.OD AND EO.OD <= EH.ED
    
    0 讨论(0)
  • 2021-01-19 19:31

    SQLFiddle demo

    SELECT EH.*, EO.OVERTIME_DATE 
    FROM EMPLOYEE_HOLIDAYS EH
    JOIN EMPLOYEE_OVERTIMES EO
    ON (EO.EMPLOYEE_ID = EH.EMPLOYEE_ID) AND 
       (EO.OVERTIME_DATE BETWEEN EH.START_DATE AND EH.END_DATE)
    
    0 讨论(0)
  • 2021-01-19 19:44

    Would this work?

    SELECT
      EO.Employee_ID,
      EH.Start_Date,
      EH.End_Date,
      EO.OverTime_Date
    FROM
      EMPLOYEE_OVERTIMES EO INNER JOIN
      EMPLOYEE_HOLIDAYS EH ON EO.Employee_ID = EH.Employee_ID
    WHERE
      EO.Overtime_Date BETWEEN EH.Start_date and EH.End_Date
    
    0 讨论(0)
提交回复
热议问题