1

我想找到当月休假次数最多的员工。

我从这个查询开始:

select MAX(TotalLeaves) as HighestLeaves 
FROM (SELECT emp_id, count(adate) as TotalLeaves 
      from attendance 
      group by emp_id) AS HIGHEST;

但是我在显示员工 ID 并仅获得当月的结果时遇到了问题。请帮帮我。

4

2 回答 2

0

如果您只想在当前查询中显示相应的employee_id,您可以对结果进行排序并获取前1行,并且您需要在分组之前过滤数据以仅获取当前月份:

select
    emp_id, TotalLeaves
from (
    select emp_id, count(adate) as TotalLeaves 
    from attendance
    where adate >= date_trunc('month', current_date)
    group by emp_id
) as highest
order by TotalLeaves desc
limit 1;

实际上,您根本不需要在这里使用子查询:

select emp_id, count(adate) as TotalLeaves 
from attendance
where adate >= date_trunc('month', current_date)
group by emp_id
order by TotalLeaves desc
limit 1;

sql fiddle demo

于 2013-11-01T08:53:30.993 回答
0
SELECT emp_id, count(adate) as TotalLeaves 
  from attendance
  where adata > date_trunc('month', NOW())
  group by emp_id
  order by 2 desc limit 1
于 2013-11-01T08:56:14.040 回答