MySQL没有活动就会获得最长的差距

时间:2014-02-24 17:30:31

标签: mysql sql datediff

我有这张桌子

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 - 在此期间公司没有活动......我怎样才能实现它?非常感谢您的帮助

3 个答案:

答案 0 :(得分: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;

在上面的示例中,对于每条记录,您可以找到下一个已完成的项目,执行日期,然后采用最大值。

在下面的例子中,我使用连接来做同样的事情。如果您的数据集非常大,那么最好创建一个临时表并摆脱派生表。

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)

答案 1 :(得分: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

答案 2 :(得分: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)))

希望它有所帮助!!