使用 MySql 获取两个日期之间的事件

Getting Events Between Two Dates using MySql

我有这个table:http://sqlfiddle.com/#!2/b4060/2

然后我创建了两个视图如下:

-- stack 1: hire
create view HS1H as
select a.* , min(a.`Effective_Date`)
from `Table1` a
left join `Table1` b on a.`Employee_ID` = b.`Employee_ID`
and a.`Effective_Date` > b.`Effective_Date` 
where a.`Event_Type` = "1_Hire"
group by a.`Employee_ID`;

select * from `hs1h`;

-- stack 1: termination
create view HS1T as
select a.* , min(a.`Effective_Date`)
from `Table1` a
left join `Table1` b on a.`Employee_ID` = b.`Employee_ID`
and a.`Effective_Date` > b.`Effective_Date` 
where a.`Event_Type` = "5_Term"
group by a.`Employee_ID`;

select * from `hs1t`;

我想获取在第一个雇用日期和第一个任期日期之间发生的事件。我使用了下面的 qry 但没有返回任何结果:

select a.* 
from `Table1` a
join `hs1h` b on a.`Employee_ID` = b.`Employee_ID`
join `hs1t` c on a.`Employee_ID` = c.`Employee_ID`
where a.`Effective_Date` between b.`Effective_Date` and c.`Effective_Date`;

我不确定哪里出了问题。我能够 运行 以下两个问题。一个在第一次雇用日期之后返回事件,另一个在第一个任期日期之前返回事件。但是当我像上面那样组合它们时,它不起作用。

select a.* 
from `Table1` a
join `hs1h` b on a.`Employee_ID` = b.`Employee_ID`
join `hs1t` c on a.`Employee_ID` = c.`Employee_ID`
where a.`Effective_Date` > b.`Effective_Date`;

select a.* 
from `Table1` a
join `hs1h` b on a.`Employee_ID` = b.`Employee_ID`
join `hs1t` c on a.`Employee_ID` = c.`Employee_ID`
where a.`Effective_Date` < c.`Effective_Date`;
SELECT * 
FROM table1 
WHERE `effective date` 
BETWEEN (select MIN(`effective date`) from `Table1` WHERE `event type` = '1_Hire') 
AND
(select MIN(`effective date`) FROM table1 WHERE `event type` = '5_Term')

对于第 2 个或第 3 个 'hire',事情变得有点复杂,但像这样的东西应该可以工作...

SELECT a.* 
  FROM TH_Sample_Data a
  JOIN (
  SELECT x.*
     , MIN(y.effective_date) end
     , @i := @i+1 rank
  FROM TH_Sample_Data x
  JOIN TH_Sample_Data y
    ON y.effective_date >= x.effective_date
   AND y.event_type = '5_Term'
     , (SELECT @i:=1) vars
  WHERE x.event_type = '1_Hire'
  GROUP
     BY x.id
    ) b
   ON a.effective_date BETWEEN b.effective_date and b.end
WHERE b.rank = 2;