[英]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! 我有一个查询,该查询应读取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
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 请看看sqlfiddle这是我实际需要的结果
employee annual_leave sick_leave
5 7 2
6 4 1
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". 这其中需要处理的一点点的客户端代码:检查的价值leave_type
知道,如果在价值leave_days
是一个“annual_leave”或“sick_leave”。 Use 0
for the number of days for the other type of leave if it not returned by the query 如果查询未返回,请使用0
表示其他类型的请假天数
"Group by" functions such as MAX() and/or SUM() cannot be performed recursively within the same statement. 不能在同一条语句中递归执行“分组”功能,例如MAX()和/或SUM()。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.