鉴于下表,我想计算公司在不雇用任何人的情况下最长的工作天数。
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS85QTVlSC5wbmcifQ==” alt =“表的图像”>
这是我到目前为止尝试过的:
SELECT EmpID, MAX(Hire_Date-e.Hire_Date) AS maxDiff
FROM employees
LEFT JOIN employees e ON e.EmpID = employees.EmpID
AND employees.Hire_Date >= e.Hire_Date
WHERE e.Hire_Date IS NOT NULL
GROUP BY EmpID;
您要使用lag()
或lead()
:
select datediff(next_hd, hiredate) as days_since_prev_hire
from (select t.*,
lead(hiredate) over (order by hiredate) as next_hd
from t
) t
where next_hd is not null
order by datediff(next_hd, hiredate) desc;
请注意,这不包括最后的最新雇用。为此,删除where
子句并使用:
order by datediff(coalesce(next_hd, curdate()), hiredate) desc
使用ANSI SQL并将字符串转换为日期:
SELECT
empid,
STR_TO_DATE(hire_date,'%d/%m/%Y') AS hire_date,
DATEDIFF(
STR_TO_DATE(hire_date,'%d/%m/%Y'),
(SELECT MAX(STR_TO_DATE(hire_date,'%d/%m/%Y')) FROM hiring WHERE STR_TO_DATE(hire_date,'%d/%m/%Y') < STR_TO_DATE(t.hire_date,'%d/%m/%Y'))
) AS days_since_last_hiring
FROM hiring AS t ORDER BY STR_TO_DATE(hire_date,'%d/%m/%Y');
输出:
+-------+------------+------------------------+
| empID | hire_date | days_since_last_hiring |
+-------+------------+------------------------+
| 103 | 2015-02-03 | NULL |
| 407 | 2016-01-07 | 338 |
| 333 | 2016-08-07 | 213 |
| 409 | 2016-10-15 | 69 |
| 410 | 2017-01-01 | 78 |
| 413 | 2017-01-01 | 78 |
+-------+------------+------------------------+
6 rows in set (0.00 sec)
当然,最后两行与前一行具有较低日期的比较相比具有相同的差异