在mysql查询中对记录进行分组会产生错误

时间:2015-01-06 09:08:07

标签: mysql

我有一个查询应该读取leave_requests_2014表中的记录,并为每位员工的所有记录执行sum()个已接受的请假请求!

SELECT lr.emp_id employee,
ifnull(MAX(CASE WHEN lr.leave_type =2 THEN (sum((TO_DAYS(lr.end_date) - TO_DAYS(lr.start_date)+1))) END ) ,0) annual_leave,
ifnull(MAX(CASE WHEN lr.leave_type =3 THEN (sum((TO_DAYS(lr.end_date) - TO_DAYS(lr.start_date)+1))) END ),0) sick_leave
FROM leave_requests_2014 lr
WHERE lr.status =5
GROUP BY lr.emp_id

返回以下错误的查询:

#1111 - Invalid use of group function

我真的不知道应该分组什么来获得所需的输出!

请查看sqlfiddle这是我实际需要的结果

employee    annual_leave    sick_leave
   5             7              2
   6             4              1

2 个答案:

答案 0 :(得分:1)

您的查询的更简单(和更正确)版本:

SELECT lr.emp_id AS employee,
   SUM(IF(lr.leave_type = 2, DATEDIFF(lr.end_date, lr.start_date) + 1, 0)) AS annual_leave,
   SUM(IF(lr.leave_type = 3, DATEDIFF(lr.end_date, lr.start_date) + 1, 0)) AS sick_leave,
FROM leave_requests_2014 lr
WHERE lr.status = 5
GROUP BY lr.emp_id

另一个版本,甚至更简单,可以在不同的行上生成年假和病假天数(如果需要):

SELECT lr.emp_id AS employee, lr.leave_type,
   SUM(DATEDIFF(lr.end_date, lr.start_date) + 1) AS leave_days,
FROM leave_requests_2014 lr
WHERE lr.status = 5 AND lr.leave_type IN (2, 3)
GROUP BY lr.emp_id, lr.leave_type

这个需要对客户端代码进行一些处理:检查leave_type的值,以了解leave_days中的值是“annual_leave”还是“sick_leave”。如果查询未返回,则使用0表示其他类型休假的天数

答案 1 :(得分:1)

"分组"诸如MAX()和/或SUM()之类的函数不能在同一语句中递归执行。解决方案是在子查询中执行第一个聚合。例如:

SELECT employee, 
ifnull(MAX(CASE WHEN leave_type =2 THEN annual_leave END),0) annual_leave,
ifnull(MAX(CASE WHEN leave_type =3 THEN sick_leave END),0) sick_leave
FROM
    (
        SELECT lr.emp_id employee, lr.leave_type 
        (CASE WHEN lr.leave_type =2 THEN (sum((TO_DAYS(lr.end_date) - TO_DAYS(lr.start_date)+1))) END ) annual_leave,
        (CASE WHEN lr.leave_type =3 THEN (sum((TO_DAYS(lr.end_date) - TO_DAYS(lr.start_date)+1))) END ) sick_leave
        FROM leave_requests_2014 lr
        WHERE lr.status =5
        GROUP BY lr.emp_id, lr.leave_type
    ) firstAggregation
group by employee