deviloper
deviloper

Reputation: 7240

Grouping records in mysql query gives error

I have a query that should read the records in leave_requests_2014 table and do a sum() of the accepted leave requests of all records for each employe!

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

The query that returns the following error:

#1111 - Invalid use of group function

I really do not know what should be grouped to get the desired output!

Please have a look at sqlfiddle This is the result I actually need

employee    annual_leave    sick_leave
   5             7              2
   6             4              1

Upvotes: 0

Views: 38

Answers (2)

semoru
semoru

Reputation: 90

"Group by" functions such as MAX() and/or SUM() cannot be performed recursively within the same statement. A solution would be to perform the first aggregation in a sub-query. For example:

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

Upvotes: 1

axiac
axiac

Reputation: 72256

A simpler (and correct) version of your query:

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

Another version, even much simpler that produces the annual leave and the sick leave days on different rows (if needed):

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

This one needs a little bit of processing on the client code: check the value of leave_type to know if the value in leave_days is an "annual_leave" or a "sick_leave". Use 0 for the number of days for the other type of leave if it not returned by the query

Upvotes: 1

Related Questions