這裏是我的問題,我有一個MySQL表具有以下的列和數據的例子:複雜重疊
id | user | starting date | ending date | activity code
1 | Andy | 2010-04-01 | 2010-05-01 | 3
2 | Andy | 1988-11-01 | 1991-03-01 | 3
3 | Andy | 2005-06-01 | 2008-08-01 | 3
4 | Andy | 2005-08-01 | 2008-11-01 | 3
5 | Andy | 2005-06-01 | 2010-05-01 | 4
6 | Ben | 2010-03-01 | 2011-06-01 | 3
7 | Ben | 2010-03-01 | 2010-05-01 | 4
8 | Ben | 2005-04-01 | 2011-05-01 | 3
正如你可以在此表中看到用戶可以有相同的活動代碼和類似的日期週期。對於同一個用戶,期間可以重疊或不重疊。表中還可能有幾個重疊期。
我要的是一個MYSQL
查詢得到以下結果:
new id | user | starting date | ending date | activity code
1 | Andy | 2010-04-01 | 2010-05-01 | 3 => ok, no overlap period
2 | Andy | 1988-11-01 | 1991-03-01 | 3 => ok, no overlap period
3 | Andy | 2005-06-01 | 2008-11-01 | 3 => same user, same activity but ending date coming from row 4 as extended period
4 | Andy | 2005-06-01 | 2010-05-01 | 4 => ok other activity code
5 | Ben | 2005-04-01 | 2011-06-01 | 3 => ok other user, but as overlap period rows 6 and 8 for the same user and activity, I take the widest range
6 | Ben | 2010-03-01 | 2010-05-01 | 4 => ok other activity for second user
換句話說,對於相同的用戶和活動的代碼,如果沒有重疊,我需要的起始日期和結束日期爲他們是。如果同一用戶和活動代碼存在重疊,則需要來自不同相關行的較低開始日期和較高結束日期。我需要這個表的所有用戶和活動代碼的表和SQL中的MYSQL。
我希望它很清楚,有人可以幫助我,因爲我嘗試了本網站上提供的解決方案中的不同代碼,而其他人則沒有成功。
非常感謝PM,它工作的很棒。老實說,這對我來說真的太複雜了......當然,我還有很多在SQL中學習的東西。我只修改了你的代碼,以考慮當它仍然在進行時沒有結束日期('0000-00-00'作爲表中的結束日期)發生的情況。再次感謝 – user3115576