我试图找到创建票证时员工必须找到的最接近的职位。我的雇员表保留了对雇员的所有更改,即经理的更改,位置等。这是我编写的查询;
SELECT DATEDIFF(t.created, e.valid_from) "diff",
t.ticket_id,
t.assignee_id,
t.created AS 'ticket_created',
u.user_id,
u.email,
e.valid_from,
...
...
...
FROM tickets t
JOIN users u ON t.assignee_id = u.user_id
JOIN employees e ON u.email = e.email
这将为每个员工变更提供一行。如何缩小范围以仅从DATEDIFF中选择最小的正整数?这将使我获得最接近工单创建的职位。
示例输出;
ticket_id diff ticket_created job_title email
111 2 20-04-18 XYZ a@a.com
111 5 25-04-18 YYZ a@a.com
111 -30 04-01-18 ABC a@a.com
我想要的输出是仅保留第一行,因为它是差异中的最低正整数。
答案 0 :(得分:1)
尝试这样-仅获取DATEDIFF将返回正结果(大于零)的那些记录,然后按实际的DATEDIFF排序并获得其中的第一个(最小的)记录:
SELECT
t.ticket_id,
t.assignee_id,
t.created AS 'ticket_created',
u.user_id,
u.email,
(SELECT e.job_title FROM employees e
WHERE u.email = e.email AND t.created > e.valid_from
ORDER BY DATEDIFF(t.created, e.valid_from) LIMIT 1
) AS valid_from,
...
...
...
FROM tickets t
JOIN users u ON t.assignee_id = u.user_id