我們有2個表,並試圖找出如何在兩個時間段相交的情況下進行交叉連接。加入2個時間段相交
第一個表(employment
)包含4列:
EmployerID, UserID, StartDate, EndDate
第二個表(status_history
)還包含4列:
UserID, Status, StartDate, EndDate
employment
表包含記錄表示哪個的 「工作」 的每個用戶與開始日期和結束日期相關聯以及持續多久。同樣,status_history
包含記錄,顯示用戶是否處於活動/非活動狀態(僱用或失業) - 也包含StartDate和EndDate。
我們正在嘗試構建一個視圖,以在兩個表格之間創建適當的「交叉連接」。
EmployerID, UserID, Status, StartDate, EndDate
我試着創建一個SQL小提琴,但由於某種原因,我收到他們的錯誤。所以,我已經提供了以下模式:
CREATE TABLE employment
(`EmployerID` int, `UserID` int, `StartDate` date, `EndDate` date);
CREATE TABLE status_history
(`UserID` int, `Status` varchar(10), `StartDate` date, `EndDate` date);
INSERT INTO employment
(`EmployerID`, `UserID`, `StartDate`, `EndDate`)
VALUES
(123, 111, '2017-01-01', '2017-03-04'),
(345, 111, '2017-03-04', '2017-03-07'),
(567, 111, '2017-03-07', '2017-04-10'),
(789, 111, '2017-04-10', NULL)
;
INSERT INTO status_history
(`UserID`, `Status`, `StartDate`, `EndDate`)
VALUES
(111, 'Active', '2017-01-01', '2017-02-17'),
(111, 'Inactive', '2017-02-17', '2017-03-02'),
(111, 'Active', '2017-03-02', '2017-03-09'),
(111, 'Inactive', '2017-03-09', NULL),
;
根據這些數據,我想找回以下行:
+------------+---------+-----------+-------------+-------------+
| EmployerID | UserID | Status | StartDate | EndDate |
+------------+---------+-----------+-------------+-------------+
| 123 | 111 | Active | 2017-01-01 | 2017-02-17 |
| 123 | 111 | Inactive | 2017-02-17 | 2017-03-02 |
| 123 | 111 | Active | 2017-03-02 | 2017-03-04 |
| 345 | 111 | Active | 2017-03-04 | 2017-03-07 |
| 567 | 111 | Active | 2017-03-07 | 2017-03-09 |
| 567 | 111 | Inactive | 2017-03-09 | 2017-04-10 |
| 789 | 111 | Inactive | 2017-04-10 | NULL |
+------------+---------+-----------+-------------+-------------+
任何幫助,將不勝感激!
使用內連接。展示你試過嗎? – Rafee
我們^ h廣告嘗試了幾件事,沒有一件給了我們正確的結果。最新的查詢是從'status_history'到'employment'的一個簡單的INNER JOIN'.UserID = e.UserID AND sh.StartDate = e.StartDate AND sh.EndDate = e.EndDate' –
哪一個是唯一的' EmployerID'或'UserID'? – Rafee