SQL中的SQL连接和子查询

时间:2012-08-15 16:22:32

标签: mysql sql

我有一个表employee,其列 id (主键),* employee_name *和另一个名为employee_works的表,其中列为* employee_id *(外键引用员工。 id),* start_date *(datetime),* finish_date *(datetime)。

以下是员工表的一些数据:

 **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

我还希望得到员工在另一栏中工作的总天数?

2 个答案:

答案 0 :(得分:1)

问题是您有一个分组但没有聚合来定义状态。 Mysql不会给你一个语法错误。相反,它会为您提供随机状态:

尝试这样的事情:

select id, name,
       (CASE WHEN statusint = 3
             THEN 'Still working'
             WHEN statusint = 1 or statusint is null
             THEN 'Never Worked'
             WHEN statusint = 2
             THEN 'Left'
        END) AS status,
       days_worked
from (SELECT emp.id, emp.name,
             max(CASE WHEN occ.departure_date is NULL and occ.start_date is NOT NULL
                      THEN 3
                      WHEN occ.departure_date is NULL and occ.start_date is NULL
                      THEN 1
                      WHEN occ.departure_date is NOT NULL and occ.start_date is NOT NULL
                      THEN 2
                 END) AS statusint,
             sum(datediff(coalesce(departure_date, curdate()), occ.start_date
                ) as days_worked
      FROM employee emp LEFT JOIN
           employee_works occ
           ON emp.id=occ.employee_id
      GROUP BY emp.id, emp.name
     ) eg

mysql的这个“功能”称为隐藏列。编写mysql的人(以及许多使用它的人)认为这是一个很棒的功能。许多使用其他数据库的人只是抓住了头脑,想知道为什么任何数据库都会如此奇怪。

顺便说一句,你应该检查一下多次受雇的人是否被分配了新的身份证。如果是这样,您的查询可能需要更高级的名称匹配方法。

答案 1 :(得分:0)

尽量简化您的病情。

SELECT  a.*, 
        CASE
            WHEN b.employeeID IS NULL THEN 'NEVER WORKED'
            WHEN b.finish_date IS NULL THEN 'STILL WORKING'
            WHEN DATE(b.finish_date) < CURDATE() THEN 'LEFT'
        END as `Status`
FROM    employee a
            LEFT JOIN employee_works b
                on a.id = b.employeeID