我有一个表employee
,其中包含列id(主键)、*employee_name* 和另一个表employee_works
,其中包含列 *employee_id*(引用employee.id 的外键)、*start_date*(日期时间)、*finish_date*(日期时间)。
以下是员工表的一些数据:
**id** **employee_name**
1 employee A
2 employee B
3 employee C
4 employee D
5 employee E
6 employee F
7 employee G
employee_works 表:
1 2010-01-01 00:00:00 NULL
2 2010-01-01 00:00:00 2010-01-10 10:00:00"
2 2010-01-13 00:00:00 2010-01-15 10:00:00"
2 2010-01-31 00:00:00 NULL
4 2010-02-18 00:00:00 2011-01-31 00:00:00"
6 2010-02-18 00:00:00 NULL
NULL 值表示员工仍在工作。我需要一个查询来显示员工中的人员列表,如果他们与我们一起工作,谁仍在我们公司工作,谁离开了,如果可能的话,他们与我们一起工作了多长时间。例子:
id employee_name status
1 Employee A Still with us
3 Employee C Never worked
4 Employee D Left
我的尝试:
SELECT emp.id,emp.name,
CASE
WHEN occ.finish_date is NULL and occ.start_date is NOT NULL THEN 'Still working'
WHEN occ.finish_date is NULL and occ.start_date is NULL THEN 'Never Worked'
WHEN occ.finish_date is NOT NULL and occ.start_date is NOT NULL THEN 'Left'
END
AS status
FROM employee AS emp
LEFT JOIN employee_works AS occ ON emp.id=occ.employee_id
GROUP BY emp.id, occ.finish_date
我还想获得员工在另一列中工作的总天数?