高级MySQL查询

时间:2014-09-16 10:22:14

标签: mysql sql

  Employees
  EmpID : int(10)
  Firstname: varchar(100)
  Lastname: varchar(100)
  HireDate: timestamp
  TerminationDate: timestamp

  AnnualReviews
  EmpID: int(10)
  ReviewDate: timestamp

什么是查询计算公司没有雇用或解雇任何人的最长时间(以天为单位)。

到目前为止,这是我的查询:

SELECT max(abs(datediff((select max(terminationdate) 
                         from employees 
                         where terminationdate < t.terminationdate),
               terminationdate))),
max(abs(datediff((select max(hiredate) 
                  from employees 
                  where hiredate <  t.hiredate), 
         hiredate)))
FROM employees AS t

我不知道如何比较同一场的每一行的日期..

1 个答案:

答案 0 :(得分:1)

然而,这是一项艰难的任务......

 SELECT x.date, MIN(y.date) y_date,DATEDIFF(MIN(y.date),x.date) days
FROM
(
SELECT hiredate date FROM employees
UNION 
SELECT terminationdate FROM employees
) x
JOIN
(
SELECT hiredate date FROM employees
UNION 
SELECT terminationdate FROM employees
UNION
SELECT CURDATE())
y
ON y.date > x.date
GROUP BY x.date
ORDER BY days DESC LIMIT 1;