2014-02-24 40 views
0

最長的空白我有這個表MySQL的獲得沒有活動

CREATE TABLE staff (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `firstname` varchar(32), 
    `surname` varchar(32), 
    `dateEnrollment` date, 
    `dateCompletion` date, 
    PRIMARY KEY (`id`) 
); 

INSERT INTO staff (`firstname`, `surname`, `dateEnrollment`, `dateCompletion`) VALUES 
('Demo', 'Demo', '2010-01-13', '2010-02-13'), 
('Jone', 'Borek', '2010-02-14', '2011-03-13'), 
('Denis', 'Koszi', '2010-02-15', '2010-06-13');

,我需要SQL查詢,返回我的時間最長,沒有任何活動。例如:Jone Borek完成2011-03-13到Denis Koszi完成2010-06-13 - 在這個時期是沒有活動的公司...我該如何實現它?求助

回答

0

下列任一會的工作, 非常感謝(我更喜歡後者):

SELECT 
MAX(DATEDIFF(
(SELECT MIN(s2.dateCompletion) 
    FROM staff s2 
    WHERE s2.dateCompletion >= s.dateCompletion AND s2.id != s.id) 
, dateCompletion)) 
from staff s; 

在上面的例子中,對於每個記錄,你會發現一個已完成的項目,做一個DATEDIFF,然後取最大值。

在下面的例子中,我使用連接來做同樣的事情。如果你的數據集非常大,那麼最好創建一個臨時表並擺脫派生表。

SELECT 
MAX(DATEDIFF(s2.dateCompletion, s.dateCompletion)) 
FROM staff s 
JOIN staff s2 ON s2.dateCompletion = (SELECT MIN(s3.dateCompletion) 
    FROM staff s3 
    WHERE s3.dateCompletion >= s.dateCompletion 
     AND s3.id != s.id) 

而且,你測量閒置最長期限,也願意爲包括MAX(dateCompletion)和CURDATE()之間的時間差,然後使用以下命令:

SELECT 
MAX(DATEDIFF(COALESCE(s2.dateCompletion, CURDATE()), s.dateCompletion)) 
FROM staff s 
JOIN staff s2 ON s2.dateCompletion = (SELECT MIN(s3.dateCompletion) 
    FROM staff s3 
    WHERE s3.dateCompletion >= s.dateCompletion 
     AND s3.id != s.id) 
+0

你的第一個代碼正是我需要的!謝謝! – user3347718

0

嘗試:

SELECT s1.id id1, 
     s1.firstname firstname1, 
     s1.surname surname1, 
     s1.`dateCompletion` dateCompletion1, 
     s2.id id2, 
     s2.firstname firstname2, 
     s2.surname surname2, 
     s2.`dateCompletion` dateCompletion2, 
     datediff(s1.`dateCompletion`, s2.`dateCompletion`) 
FROM staff s1 
JOIN staff s2 
ON s1.`dateCompletion` = (
     SELECT min(dateCompletion) 
     FROM staff s3 
     WHERE s3.dateCompletion > s2.`dateCompletion` 
) 
ORDER BY datediff(s2.`dateCompletion`, s1.`dateCompletion`) 
LIMIT 1 

演示:http://sqlfiddle.com/#!2/c1e939/8

+0

感謝它的作品:) – user3347718

0
select x.firstname as firstname1,x.surname as surname1,y.firstname as firstname2,y.surname as surname2,MIN(ABS(DATEDIFF(x.dateEnrollment,x.dateCompletion)-DATEDIFF(y.dateEnrollment,y.dateCompletion))) AS parameter 
    from staff x join staff y on 
    x.dateEnrollment <= y.dateCompletion and y.dateEnrollment <= x.dateCompletion and x.firstname!=y.firstname and x.surname!=y.surname 

這將給出兩個人的細節以及參數值,如果這是您的問題的含義,那麼這兩個參數值應該是最小的,以使這兩個人保持最長的時間。 如果需要,您還可以在結果中添加日期。

另外一個更快的方式將與having子句中使用它:

select x.firstname as firstname1,x.surname as surname1,y.firstname as firstname2,y.surname as surname2 
    from staff x join staff y on 
    x.dateEnrollment <= y.dateCompletion and y.dateEnrollment <= x.dateCompletion and x.firstname!=y.firstname and x.surname!=y.surname HAVING MIN(ABS(DATEDIFF(x.dateEnrollment,x.dateCompletion)-DATEDIFF(y.dateEnrollment,y.dateCompletion))) 

希望它可以幫助!